Array vs array [] for java

I am writing a program that will rely heavily on ... something ... that stores data, such as an array, where I can access any data point at any point in time, as I can, in the array.

I know that in the java library there is an Array class that I could use, or I could use a raw array [].

I expect using an Array type is a little easier to code, but I expect it to be slightly less efficient.

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

+4
source share
4 answers

In fact, Array wouldn't help - it's not what you think. The java.util.ArrayList class, on the other hand. In general, if you can program collection classes like ArrayList , do it - it will be easier for you to get the right, flexible software, which is also easier to read. And this “if” applies almost all the time; raw arrays are what you use as a last resort or, most often, when the method you want to call requires one as an argument.

+5
source

The Array class is used to reflect Java and is very, very rarely used.

If you want to store data in an array, use plain old arrays, indicated by the symbol [] , or, as Gabe answers to the question, java.util.ArrayList . ArrayList , as your comment suggests making the code easier (when it comes to adding and removing elements!), But yes, a little less efficient. For variable-size collections, an ArrayList is required only.

+3
source

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

It depends on what you are trying to achieve:

  • If the number of elements in the array is known in advance, then the type of array is appropriate. If not, the List type is (at least) more convenient to use.

  • The List interface offers a number of methods, such as contains , insert , remove , etc., that can save you when coding ... if you need to do something.

  • When used correctly, the array type will use less space. The difference is especially important for arrays of primitive types, where using List means that elements must be represented using wrapper types (for example, byte becomes byte ).


The Array class is not useful in this context, and is not an Arrays class. Choosing between an ArrayList (or some other List implementation class) and primitive arrays.

+2
source

In terms of ease of use, the Array class is much easier to code. The array [] is a rather complicated problem in terms of the fact that you need to know the size of the list of objects in advance.

Instead, you can use a HashMap. It is very effective for searching, and also for sorting the whole process is performed in terms of key values.

You can declare a HashMap as:

 HashMap<String, Object> map = new HashMap<String, Object>(); 

You can use your class for an object, and for a key, use a value that must be unique.

-2
source

All Articles