aspose file tools*
The moose likes Beginning Java and the fly likes initializing ArrayList Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "initializing ArrayList" Watch "initializing ArrayList" New topic
Author

initializing ArrayList

Bill Jones
Greenhorn

Joined: Aug 26, 2007
Posts: 2
I am missing something simple and fundamental. Maybe you guys can help.

With an "old-style" array, I can initialize it like this:
int[] myArray = new int[]{ 2000, 100, 40, 60};

With an ArrayList, it seems like I have to do
ArrayList<Integer> myArray = new ArrayList<Integer>();
myArray.add(2000)
myArray.add(100)
myArray.add(40)
myArray.add(60)
for each element that I want to add. Is there a way that I can add any number of integers to my ArrayList in a single line of code?

Any ideas?
Freddy Wong
Ranch Hand

Joined: Sep 11, 2006
Posts: 959

As far as I know, there isn't a way to initialize the ArrayList as what you normally do with Java array. But of course, there's nothing stopping you from creating a method to do such a thing
For example:


SCJP 5.0, SCWCD 1.4, SCBCD 1.3, SCDJWS 1.4
My Blog
Bill Jones
Greenhorn

Joined: Aug 26, 2007
Posts: 2
You're the man, Freddy Wong. Here is what I did that worked. Since I won't always know the number of integer elements in the array, I decided to pass in an "old-style" array to the initArrayList method. Thank you!

main:
ArrayList<Integer> note = new ArrayList<Integer>();
int[] myArray = new int[]{ 58,63,67,72,70,63,62,63 };
note = initArrayList(myArray);


method:
public ArrayList<Integer> initArrayList(int[] a) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i : a) {
list.add(i);
} //close for loop
return list;
} //close initArrayList method
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
You can also do this:

But note the List returned from Arrays.asList() is fixed size. If you need a non fixed-size List you can do this:


Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
didi Dji
Greenhorn

Joined: May 09, 2008
Posts: 1
I know that the post is old but I just wanted to make BIG thanks to Freddy Wong and specially to Garrett Rowe for their replies cause it was EXACLTY what I was looking for . I was so happy to find it cause I've been searching for more than 1 hour on the API of sun and on google without finding something very nice x).I'm very happy and I just wanted to say :

Thank you a loooooot ^__^


<a href="http://parrainage.neuf.free.fr/" target="_blank" rel="nofollow">http://parrainage.neuf.free.fr/</A> <a href="http://parrainages.ing.free.fr/" target="_blank" rel="nofollow">http://parrainages.ing.free.fr/</A>
Manuel Leiria
Ranch Hand

Joined: Jul 13, 2007
Posts: 171
How about,



Manuel Leiria<br /> <br />--------------<br />Peace cannot be kept by force; it can only be achieved by understanding. <br /> Albert Einstein
Evelina Vrabie
Greenhorn

Joined: Oct 10, 2008
Posts: 19
Manuel Leiria wrote:How about,



Or ArrayList<Integer> arr = new ArrayList<Integer>() {{ add(30); add(40); }}; Same syntax can be used with Map (use put instead of add)


Evelina Vrabie
SCJP 6, SCJD (in progress)
Larry Swanson
Greenhorn

Joined: Jun 23, 2008
Posts: 2
This thread is ancient, but here's another method I saw in a seminar with Adam Bien.



I'm not quite sure what's going on here though...

Larry
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19719
    
  20

It creates an anonymous subclass of ArrayList (the outer pair of {}). This anonymous subclass has an initializer block (the inner pair of {}) which executes the add methods. It's a nasty little hack that should be avoided.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14269
    
  21

That trick is called "double brace initialization". I agree with Rob that it's a dirty trick that should be avoided.

(Note that Evelina Vrabie already mentioned this trick in her post of April 9, 2009).


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Anish Kurian Thomas
Greenhorn

Joined: Jun 26, 2009
Posts: 21

There is another way you can do this :


SCJP 4 (88%) | SCJP 6 (88%) | SCWCD 5 (100%) | SCBCD 5 (96%) | SCDJWS 5 in progress
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Anish Kurian Thomas wrote:There is another way you can do this :


You could do that, but only if you enjoy ClassCastExceptions, because that's what you'd get. Arrays.asList() does not return an ArrayList.


[Jess in Action][AskingGoodQuestions]
Anish Kurian Thomas
Greenhorn

Joined: Jun 26, 2009
Posts: 21

Sorry .. I was wrong.. Thank you Ernest Friedman-Hill for pointing this out.

I believe the code will work by changing into:


Vinay M Raju
Greenhorn

Joined: Aug 01, 2011
Posts: 3
Very useful information. Thansk a lot !!
Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4347
    
    2

very interesting topic but i would have just used an array


SCJP
Visit my download page
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8008
    
  22

Vinay M Raju wrote:Very useful information. Thansk a lot !!

It should be pointed out that Anish's code is redundant. What Ernest was trying to highlight is that Arrays.asList() returns a List, not an ArrayList (actually, the List is an ArrayList - at least right now - but you shouldn't take it for granted).

It's almost invariably best to use interfaces anyway, so far better is:
List<Integer> myArray = Arrays.asList(1,2,3);

Randall Twede wrote:very interesting topic but i would have just used an array

Then you're missing out. Apart from fixed-length primitive arrays and String.split(), I hardly ever use them any more.

Winston


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3647
    
  17

If you really must have an ArrayList, what you can also do is the following:
This makes use of the fact that every concrete collection type is supposed to have a constructor that copies the elements from an existing collection; in this case the new ArrayList copies the elements from the List returned by the asList() method.

[edit]

Wow, never mind, I completely missed Anish's example.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: initializing ArrayList