• 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?

 
Divyadharshini Karthikeyan
Ranch Hand
Posts: 33
  • 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);
 
Stephan van Hulst
Saloon Keeper
Posts: 10433
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.
 
Mike Simmons
Rancher
Posts: 3305
28
  • 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: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for clarifying.
 
Campbell Ritchie
Marshal
Posts: 65114
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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!