2
public static void main(String[] args) {
    LinkedList test = new LinkedList();
    int[] numberPair;
    numberPair = new int[2];
    numberPair[0] = 1; numberPair[1] = 2;

    test.add(numberPair);

}

How would I go about accessing the array in the first node of this list and printing it? I've tried all kinds of casting with test.getFirst(), but either it prints out the memory address or I get a long list of casting errors for objects.

3 Answers 3

4

Try using Arrays.toString().

See the javadoc for details.

Edit:

As other answers have pointed out, you should also use generics with your List. You should declare it as a LinkedList<int[]>. And then as you iterate over the elements, use Arrays.toString to convert each element into a string and print the result.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, all I needed to do was declare it with <int[]>, and Arrays.toString started working. I'm not sure why it would affect that, but, hey, it works.
@user1204458: Unless you use <int[]> (or explicitly cast the element into int[] after getting it from the list) it is considered to be an Object. You can't apply Arrays.toString() on an Object since it expects a int[].
1

If using java 1.5+ use java generics like so:

LinkedList<int[]> test = new LinkedList<int[]>();
int[] top = test.getFirst();
for (int i: top){
   System.out.print(i+" ");
}
System.out.println();

Comments

1

You should use a generic type instead of a raw type.

LinkedList<int[]> test = new LinkedList<int[]>();

When do test.getFirst(), you are getting an int array back, so just iterate through it.

int[] bla = test.getFirst();

for ( int i : bla )
    System.out.println(i);

Or use

Arrays.toString(test.getFirst());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.