Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array vs array [] for java

Tags:

java

I am writing a program that will be heavily reliant on ... something ... that stores data like an array where I am able to access any point of the data at any given time as I can in an array.

I know that the java library has an Array class that I could use or I could use a raw array[].

I expect that using the Array type is a bit easier to code, but I expect that it is slightly less efficient as well.

My question is, which is better to use between these two, and is there a better way to accomplish the same result?

like image 342
Andy Avatar asked Feb 24 '23 01:02

Andy


2 Answers

Actually Array would be of no help -- it's not what you think it is. The class java.util.ArrayList, on the other hand, is. In general, if you can program with collection classes like ArrayList, do so -- you'll more easily arrive at correct, flexible software that's easier to read, too. And that "if" applies almost all the time; raw arrays are something you use as a last resort or, more often, when a method you want to call requires one as an argument.

like image 65
Ernest Friedman-Hill Avatar answered Feb 25 '23 16:02

Ernest Friedman-Hill


The Array class is used for Java reflection and is very, very, rarely used.

If you want to store data in an array, use plain old arrays, indicated with [], or as Gabe's comment on the question suggests, java.util.ArrayList. ArrayList is, as your comment suggests easier to code (when it comes to adding and removing elements!!) but yes, is slightly less efficient. For variable-size collections, ArrayList is all but required.

like image 32
Ray Toal Avatar answered Feb 25 '23 16:02

Ray Toal