In this example method :

 

public void printArray(int[] input){
	for(int value : input){
    	System.out.println("%d", value);
    }
}

 

Imagine that we also want similar methods that deal with arrys of String, Doubles or other types.

We could write a new identical methods for each type of array, but that would create a lot of repetitive code.

 

To avoid writing the same method over & over again with different types, we can instead write a generic method like this:

public <E> void printArray(E[] input){
	for ( E element : input){
    	System.out.println("%s", element);
    }
}

 

Notice that we haver replaced references to a specific type int with E;

our generic type. this allows the method to accept any type of array.

 

Also notice the <E> before the method's return type (in this case void); this is the method's type parameter, and is necessary for defining a generic method.

 

We can now use this method to print all of our project's arrays

'Java - English ver' 카테고리의 다른 글

Using bounded type parameters in generic methods  (3) 2024.11.08
Type Inference in Generic Methods  (3) 2024.11.07
Writing genenric methods  (0) 2024.11.05
Wildcards Extras  (0) 2024.11.04
Using lower bounded wildcards  (0) 2024.11.03

+ Recent posts