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 arrays of String, Doubles or other types.

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

 

* repetitive 반복적인 deal 거래

 

To aboid 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 have replaced references to a specific type int with E;

out generic type. This allows the method to accept any type of array.

 

Also notice the<E> befroe 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' 카테고리의 다른 글

Type Inference in Generic Methods  (3) 2024.11.07
Writing generic methods  (0) 2024.11.06
Wildcards Extras  (0) 2024.11.04
Using lower bounded wildcards  (0) 2024.11.03
Upper bounded wildcards  (0) 2024.10.31

+ Recent posts