arraylist >to> array >to> arraylist troubles
still pretty new to java here.
ive been trying to figureout arrays and arraylists. i understand that arraylists can only store objects. I half figured out this simple code and half found things around the net to make it work:
import java.util.*;
public class G
{
public static void main(String[] args)
{
ArrayList<Integer> num = new ArrayList<Integer>();//Com 1 //
for(int f = 1; f <8; f++)
{
num.add(f);
}
Integer[] int1 = num.toArray(new Integer[0]); // Qu. 1 //
for(int i = 0; i < int1.length; ++i)
{
Integer valueInside = int1[i];
System.out.print(valueInside+ " ");
}
System.out.println();
List<Integer> int2 = Arrays.asList(int1);
for(int j= 1; j<=int2.size();j++)
{
Integer i3 = j; System.out.print(i3+ " ");
}
}
}
comment:
ArrayList<Integer> num = new ArrayList<Integer>();//Com 1 //
This i get; new arraylist called num
when I found this part of the code though it was
List<Integer> num = new ArrayList<Integer>(); why does it work either way?
Integer[] int1 = num.toArray(new Integer[0]); // Qu. 1 //
This i dont get.
we are taking the arraylist and putting the contents into a wrapper class first? why cant we just say right off the bat:
int[] int1 = new int[]; or something along those lines
and what is with the what is inside the brackets?
lastly:
is there anyway to go from an arraylist to an array without using toArray()?
Thanks!
[1816 byte] By [
shabam] at [2007-11-11 8:18:15]

# 1 Re: arraylist >to> array >to> arraylist troubles
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:
//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:
//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:
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.
arul at 2007-11-11 22:35:52 >
