4

I am trying to do some basic stuff with java. I know how to do arrays, but not ArrayList.

" Write a single Java statement that declares and initializes an ArrayList of integers named values"

For a simple array I used int [] values ;

so far I have come up with this, but Im not sure if its correct.

new ArrayList<Integer>(Arrays.asList(values));
2
  • 1
    What are you asking? Have you tried writing that in a class and compiling, then run it? Does it do what you expect? Commented Feb 22, 2014 at 22:53
  • stackoverflow.com/questions/2760995/… Commented Feb 22, 2014 at 22:54

3 Answers 3

2

This is how you would initialize an ArrayList of Integers named values:

List<Integer> values = new ArrayList<Integer>();

ArrayList implements the List inteface and extends AbstractList.

Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.

I would recommend going through a tutorial on ArrayLists as they are frequently used in the real world and you should know some of the methods that accompany the ArrayList class.

Source

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

1 Comment

I think you forgot > after the first Integer. Thank You for Helping.
0

Almost right. But Arrays.asList() returns an ArrayList, so all you have to do is declare an ArrayList<Integer> and assign the result of the method call to it.

2 Comments

No, asList returns a List which is actually an Arrays.ArrayList. This is a private class which is not the same thing as a java.util.ArrayList.
Ah, well. That's what I get for not looking up the documentation before I answer questions. I should probably delete this answer.
0

It should work

ArrayList<Integer> f = new ArrayList(Arrays.asList(values));

I use eclipse as an editor.

1 Comment

Your code compiles but it's wrong. The OP has an int[]. This only compiles because you have a raw type and you will get a ClassCastException if you try to get anything from the list.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.