• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

initializing ArrayList

 
Greenhorn
Posts: 2
  • Number of slices to send:
    Optional 'thank-you' note:
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?
 
Ranch Hand
Posts: 959
  • 1
  • Number of slices to send:
    Optional 'thank-you' note:
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:
 
Bill Jones
Greenhorn
Posts: 2
  • Number of slices to send:
    Optional 'thank-you' note:
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
 
Ranch Hand
Posts: 1296
  • Number of slices to send:
    Optional 'thank-you' note:
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:
 
Greenhorn
Posts: 1
  • Number of slices to send:
    Optional 'thank-you' note:
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 ^__^
 
Ranch Hand
Posts: 171
  • 1
  • Number of slices to send:
    Optional 'thank-you' note:
How about,

 
Greenhorn
Posts: 19
  • Number of slices to send:
    Optional 'thank-you' note:

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)
 
Greenhorn
Posts: 2
  • Number of slices to send:
    Optional 'thank-you' note:
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
 
Sheriff
Posts: 22784
131
  • Number of slices to send:
    Optional 'thank-you' note:
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.
 
Java Cowboy
Posts: 16084
88
  • Number of slices to send:
    Optional 'thank-you' note:
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).
 
Greenhorn
Posts: 21
  • Number of slices to send:
    Optional 'thank-you' note:
There is another way you can do this :
 
author and iconoclast
Posts: 24207
46
  • Number of slices to send:
    Optional 'thank-you' note:

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.
 
Anish Kurian Thomas
Greenhorn
Posts: 21
  • Number of slices to send:
    Optional 'thank-you' note:
Sorry .. I was wrong.. Thank you Ernest Friedman-Hill for pointing this out.

I believe the code will work by changing into:


 
Greenhorn
Posts: 3
  • Number of slices to send:
    Optional 'thank-you' note:
Very useful information. Thansk a lot !!
 
Ranch Hand
Posts: 4716
9
  • Number of slices to send:
    Optional 'thank-you' note:
very interesting topic but i would have just used an array
 
Bartender
Posts: 10780
71
  • Number of slices to send:
    Optional 'thank-you' note:

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
 
Saloon Keeper
Posts: 15608
366
  • Number of slices to send:
    Optional 'thank-you' note:
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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic
vceplus-200-125    | boson-200-125    | training-cissp    | actualtests-cissp    | techexams-cissp    | gratisexams-300-075    | pearsonitcertification-210-260    | examsboost-210-260    | examsforall-210-260    | dumps4free-210-260    | reddit-210-260    | cisexams-352-001    | itexamfox-352-001    | passguaranteed-352-001    | passeasily-352-001    | freeccnastudyguide-200-120    | gocertify-200-120    | passcerty-200-120    | certifyguide-70-980    | dumpscollection-70-980    | examcollection-70-534    | cbtnuggets-210-065    | examfiles-400-051    | passitdump-400-051    | pearsonitcertification-70-462    | anderseide-70-347    | thomas-70-533    | research-1V0-605    | topix-102-400    | certdepot-EX200    | pearsonit-640-916    | itproguru-70-533    | reddit-100-105    | channel9-70-346    | anderseide-70-346    | theiia-IIA-CIA-PART3    | certificationHP-hp0-s41    | pearsonitcertification-640-916    | anderMicrosoft-70-534    | cathMicrosoft-70-462    | examcollection-cca-500    | techexams-gcih    | mslearn-70-346    | measureup-70-486    | pass4sure-hp0-s41    | iiba-640-916    | itsecurity-sscp    | cbtnuggets-300-320    | blogged-70-486    | pass4sure-IIA-CIA-PART1    | cbtnuggets-100-101    | developerhandbook-70-486    | lpicisco-101    | mylearn-1V0-605    | tomsitpro-cism    | gnosis-101    | channel9Mic-70-534    | ipass-IIA-CIA-PART1    | forcerts-70-417    | tests-sy0-401    | ipasstheciaexam-IIA-CIA-PART3    | mostcisco-300-135    | buildazure-70-533    | cloudera-cca-500    | pdf4cert-2v0-621    | f5cisco-101    | gocertify-1z0-062    | quora-640-916    | micrcosoft-70-480    | brain2pass-70-417    | examcompass-sy0-401    | global-EX200    | iassc-ICGB    | vceplus-300-115    | quizlet-810-403    | cbtnuggets-70-697    | educationOracle-1Z0-434    | channel9-70-534    | officialcerts-400-051    | examsboost-IIA-CIA-PART1    | networktut-300-135    | teststarter-300-206    | pluralsight-70-486    | coding-70-486    | freeccna-100-101    | digitaltut-300-101    | iiba-CBAP    | virtuallymikebrown-640-916    | isaca-cism    | whizlabs-pmp    | techexams-70-980    | ciscopress-300-115    | techtarget-cism    | pearsonitcertification-300-070    | testking-2v0-621    | isacaNew-cism    | simplilearn-pmi-rmp    | simplilearn-pmp    | educationOracle-1z0-809    | education-1z0-809    | teachertube-1Z0-434    | villanovau-CBAP    | quora-300-206    | certifyguide-300-208    | cbtnuggets-100-105    | flydumps-70-417    | gratisexams-1V0-605    | ituonline-1z0-062    | techexams-cas-002    | simplilearn-70-534    | pluralsight-70-697    | theiia-IIA-CIA-PART1    | itexamtips-400-051    | pearsonitcertification-EX200    | pluralsight-70-480    | learn-hp0-s42    | giac-gpen    | mindhub-102-400    | coursesmsu-CBAP    | examsforall-2v0-621    | developerhandbook-70-487    | root-EX200    | coderanch-1z0-809    | getfreedumps-1z0-062    | comptia-cas-002    | quora-1z0-809    | boson-300-135    | killtest-2v0-621    | learncia-IIA-CIA-PART3    | computer-gcih    | universitycloudera-cca-500    | itexamrun-70-410    | certificationHPv2-hp0-s41    | certskills-100-105    | skipitnow-70-417    | gocertify-sy0-401    | prep4sure-70-417    | simplilearn-cisa    |
http://www.pmsas.pr.gov.br/wp-content/    | http://www.pmsas.pr.gov.br/wp-content/    |