Tuesday, March 25, 2008

JAVA Generics with ArrayList as parameter

The following code show the use of Java Generic.
Generally if sum function accepting the list of int value we will use int[] value as the parameter and while calling it we will use

int sum = sum(new int[]{1,2,3,4}); some thing like this but it looks some odd.

So, now with the generic u can perform same operation using following code.

public class GenericTest {

public static void main(String[] args) {
int sum = sum(1,2,3,5,6);
System.out.println("Sum Result :: " + sum);
}

public static int sum(int... value) {
int sum=0;

for (int i : value) {
sum+=i;
}
return sum;
}
}


Regards

No comments:

Contributors