• 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

How to declare an ArrayList

 
Ranch Hand
Posts: 260
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Which of the following two definitions is better?
Is there a better way than the following two definitions?

 
Marshal
Posts: 79153
377
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please don’t add a new question to an old post. Fortunately I can split your question into a new thread.
They are both poor forms. The correct way to do it in Java7 is
In older versions of Java you would writeThe reason is that the declaration does not commit you to using an ArrayList; you could use a LinkedList or other sort of List anywhere. Your outer List could even contain several different List implementations, but they would all contain Integers.
You should only use the constructor argument 5 if you are sure you will be using 5 elements.
 
Campbell Ritchie
Marshal
Posts: 79153
377
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can use different kinds of List; you might reassign the reference like this
 
Won't you please? Please won't you be my neighbor? - Fred Rogers. Tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic