Home > Archive > Java Help > July 2006 > ArrayList Problem
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
|
|
| zecreven@gmail.com 2006-07-23, 8:00 am |
| Hello Java gurus :)
I am new to java programming. I have a problem
with Arraylist object. I wrote the program below;
import java.util.ArrayList;
public class TestDrive {
public static void main(String[] args) {
int[] test = new int[2]; //making new int array
ArrayList superList = new ArrayList(); //making ArrayList object
superList.add(test);
int [] moon = new int[2];
moon = superList.get(0); //How will I get the object reference?
}
}
I can't get the int[] array which is stored in ArrayList. if you
compile the
source code above, it returns error which is "Error(17,9): incompatible
types; found: class java.lang.Object,
required: array int[]"
please help me about this problem..
Thank you all.
| |
| Tony Morris 2006-07-23, 8:00 am |
| On Sun, 23 Jul 2006 03:55:08 -0700, zecreven wrote:
> moon = superList.get(0); //How will I get the object reference?
You need to perform a cast:
moon = (int[])superList.get(0);
--
Tony Morris
http://tmorris.net/
| |
| Patricia Shanahan 2006-07-23, 8:00 am |
| Tony Morris wrote:
> On Sun, 23 Jul 2006 03:55:08 -0700, zecreven wrote:
>
>
> You need to perform a cast:
> moon = (int[])superList.get(0);
>
Adding the case will work with any Java version. Alternatively, if it is
OK to limit the program to version 1.5 or later, use generics:
import java.util.ArrayList;
public class ArrayListTest {
public static void main(String[] args) {
int[] test = new int[2]; // making new int array
ArrayList<int[]> superList = new ArrayList<int[]>();
superList.add(test);
int[] moon = new int[2];
moon = superList.get(0);
}
}
In both cases, you are telling the compiler that you expect the
ArrayList to contain int[] references. With generics, you are making the
assertion about the whole ArrayList, with the cast you make it about the
result of a specific get call.
Patricia
| |
| zecreven@gmail.com 2006-07-24, 4:00 am |
| Thank you for your answers. Type casting works for me, but
it is good to know that java has a generics feature which is like
template
feature of C++. I like generics feature most, because on that time, i
have an option
to enforce the whole list to fit only one type.
|
|
|
|
|