ArrayList Problem

A

Alper

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.
 
L

Lasse Reichstein Nielsen

Alper said:
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
 
T

Thomas Hawtin

Alper said:
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
 
A

Alper

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,586
Members
45,085
Latest member
cryptooseoagencies

Latest Threads

Top