1. List<Integer> num = new ArrayList<Integer>(); why does it work either way?
List is an interface which is implemented by ArrayList (implementation of List). You should always try and code to interface not implementation. Look at the Java API for ArrayList.
List<Integer> num = new ArrayList<Integer>(); //better approach
because you can also use a LinkedList later on which implements List interface as well.
2. Integer[] int1 = num.toArray(new Integer[0]); // Qu. 1 //
this I do not get it.
Converting an ArrayList to an array of integers. The difference between an ArrayList and an Array is that ArrayList internally use an Array and can grow. But Array cannot grow and you need to decide the size up front something like. the above code can be re-written in simple form as follows:
Code:
//define an array of int
Integer[] int1 = new Integer[num.size()];
//convert a List to Array
num.toArray(int1);
3. Another way to convert an ArrayList to an Array:
one way is to simplify:
Code:
//define an array of int
Integer[] int1 = new Integer[num.size()];
//convert a List to Array
num.toArray(int1);
another long way is to loop through the List and assign:
Code:
int[] iArray = new int[num.size()];
for (int i=0; i<num.size();i++ ) {
Integer in = (Integer) num.get(i);
iArray[i] = in.intValue();
}
So you can do things different ways. All depends on what you want to achieve.
Bookmarks