This week's book giveaway is in the Java in General forum.
We're giving away four copies of Event Streams in Action and have Alexander Dean & Valentin Crettaz on-line!
See this thread for details.
Win a copy of Event Streams in Action this week in the Java in General forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

Can you please tell me the difference between these two lines of code?

 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. ArrayList<Integer>[] buckets=new ArrayList[3];

2. ArrayList<Integer> buckets=new ArrayList<>(3);
 
Saloon Keeper
Posts: 10421
223
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first line creates an array of size three. You can assign lists to it.

The second line creates a list with initial capacity three. You can add integers to it.
 
Rancher
Posts: 3303
27
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would add, you probably don't want the first one.  Even if you want something like a two-dimensional array, it's a bad idea to mix lists with arrays - you will tend to get confusing error messages in the future.  If you want something like this, you are probably better off with either a List of Lists, or an array of arrays.  But not an array of lists, or a list of arrays.

More likely, you just wanted a single list in the first place.  Which is what you get with line #2 above.  Just use that.
 
Divyadharshini Karthikeyan
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for clarifying.
 
Marshal
Posts: 65069
247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Mike Simmons wrote:I would add, you probably don't want the first one.  . . . .

Nor will the compiler, which objects to creating arrays of any type with <> in its name. It will compile but with a warning because you are using a raw type.
That is creating an array of Lists.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!