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));
Cœur
  • 37,241
  • 25
  • 195
  • 267
Ron00sss
  • 47
  • 4
  • 1
    What are you asking? Have you tried writing that in a class and compiling, then run it? Does it do what you expect? – SimonC Feb 22 '14 at 22:53
  • http://stackoverflow.com/questions/2760995/arraylist-initialization-equivalent-to-array-initialization – Jason White Feb 22 '14 at 22:54

3 Answers3

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

Dan
  • 2,701
  • 1
  • 29
  • 34
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.

Epiglottal Axolotl
  • 1,048
  • 8
  • 17
  • 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`. – Radiodef Feb 22 '14 at 23:09
  • Ah, well. That's what I get for not looking up the documentation before I answer questions. I should probably delete this answer. – Epiglottal Axolotl Feb 22 '14 at 23:16
0

It should work

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

I use eclipse as an editor.

Tomas
  • 156
  • 7
  • 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. – Radiodef Feb 22 '14 at 23:07