Generic Function In Java
xxxxxxxxxx
public class GenericFunction {
public static void main(String[] args) {
Integer[] intArray = {1,2,3,4,5,6,7};
Double[] doubleArray = {1.1,2.2,3.3,4.4,5.0};
Character[] charArray = {'a' , 'b' , 'c' , 'd' , 'e'};
System.out.println("Integer Array :");
genericFunction(intArray);
System.out.println();
System.out.println("Double Array : ");
genericFunction(doubleArray);
System.out.println();
System.out.println("Character Array : ");
genericFunction(charArray);
}
// Generic Function In Java
public static <T> void genericFunction(T[] nums){
for(T element : nums){
System.out.print(element + " ");
}
}
}
Any Query contect me @AkashKumar
xxxxxxxxxx
// generic methods
public <T> List<T> fromArrayToList(T[] a) {
return Arrays.stream(a).collect(Collectors.toList());
}
public static <T, G> List<G> fromArrayToList(T[] a, Function<T, G> mapperFunction) {
return Arrays.stream(a)
.map(mapperFunction)
.collect(Collectors.toList());
}
// bounded generics
public <T extends Number> List<T> fromArrayToList(T[] a) {
}
//multiple bounds
<T extends Number & Comparable>
// upper bound wildcards
public static void paintAllBuildings(List<? extends Building> buildings) {
}
// lower bound wildcard
<? super T>
xxxxxxxxxx
// Generic method example 1
<T> void fromArrayToCollection(T[] a, Collection<T> c){
for (T o: a){
c.add(o);
}
}
// Generic method example 2
public static <T extends SomeClass & SomeInterface> methodName(T o){
o.setterMethod(123);
}
// Generic method example 3
public static <T> Stack <T> loadFromArray(Object[] arr, Class<T> type){
Stack <T> stack = new StackArray<>(arr.length);
for (Object o:arr){
if (type.isInstance(o)){
stack.push( (T) o); // type checking with "isInstance" and casting. "instanceof" will not work here.
}
}
}
<Car> c = loadFromArray(object_arr_of_cars, Car.class);
xxxxxxxxxx
public <T> List<T> fromArrayToList(T[] a) {
return Arrays.stream(a).collect(Collectors.toList());
}
xxxxxxxxxx
public class Box<T> {
private T content;
public void setContent(T content) {
this.content = content;
}
public T getContent() {
return content;
}
}
xxxxxxxxxx
public static T GetQueryString<T>(string key, T defaultValue) { }