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.
Lasse Reichstein Nielsen - 23 Jul 2006 12:07 GMT
> moon = superList.get(0); //How will I get the object reference?
Use a cast:
moon = (int[]) superList.get(0);
or use Java 5 generics:
List<int[]> superList = new ArrayList<int[]>();
...
moon = superList.get(0);
/L

Signature
Lasse Reichstein Nielsen - lrn@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Thomas Hawtin - 23 Jul 2006 14:43 GMT
> int [] moon = new int[2];
>
> moon = superList.get(0); //How will I get the object reference?
In addition to Lasse Nielsen's reply, the new int[2] is redundant. You
can write just:
int[] moon;
moon = superList.get(0);
or
int[] moon = superList.get(0);
The array you created will be discarded when the variable is assigned
another value.
Tom Hawtin

Signature
Unemployed English Java programmer
http://jroller.com/page/tackline/
Alper - 24 Jul 2006 08:45 GMT
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.