This week's book giveaway is in the Other Languages forum.
We're giving away four copies of Functional Reactive Programming and have Stephen Blackheath and Anthony Jones on-line!
See this thread for details.
Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to declare an ArrayList

 
albert kao
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which of the following two definitions is better?
Is there a better way than the following two definitions?

 
Campbell Ritchie
Sheriff
Pie
Posts: 50240
79
  • Likes 1
  • Mark post as helpful
  • send pies
  • 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
Sheriff
Pie
Posts: 50240
79
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use different kinds of List; you might reassign the reference like this
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic