What is faster: ArrayList of int [] or int [][] [duplicate] - java

This question already has answers here:
Java class vs array memory size?
(3 answers)
Closed 8 years ago.
Which is more efficient, take less memory, faster to loop through and why?
case 1 :
ArrayList<int [9]>
case 2:
int [9][9]
Thank you

[Assuming you meant ArrayList<> rather than Array<>, since the latter is impossible].
By all technical measures, a native array will always be faster and smaller than an ArrayList<>, although the difference may in many cases be very minimal. Internally an ArrayList uses a native array to store its elements, so it cannot possibly outperform that array.
However the ArrayList<E> has the advantage that it implements all of the List<E> interface as well as Collection<E> and Iterable<E>. This can make your code far simpler by allowing you to directly pass the object to any function that will accept parameters that implement those interfaces.
A further advantage of ArrayList<E> is that the array can transparently grow in size so it may be preferred if you do not know in advance how large the array has to be. However that itself comes at a performance cost - if the new size is larger than the current capacity of the backing store array then a whole new array must be created, and then the original elements all copied into it - an O(n) operation.

I think you meant ArrayList?
if thats is what you meant: then an array (int[][]) is always faster than the list ArrayList<Integer[]>
Because ArrayList uses an array, and everytime you remove a value, it rewrites the whole array.
Conclusion: unless you are going to consistently remove/add values NOT to the end of your "array", use a regular array (int[][]), but if you will, use ArrayList<int[]>

Array of int[] and int[][] are the same thing, called by different names. Considering that only one declaration is valid in java (the int[][]), whats the question?

Related

Copying an array or forcing an initial size on ArrayList. What is more efficient?

I'm trying to make a mutable list (list in a non programming sense) of values. The list is to be a predecided length n.
My first choice was to use an array initialized to n. But since an array isn't mutable, the only choice I have if I want to add another value is to copy the array into an array of bigger size. I decided to try using an ArrayList instead.
Then the trade off is that I can't set the ArrayList to an initial size n. However, I can add values to the ArrayList, since it's mutable. So I'm wondering whether it would be more efficient to create an array then copy it into a bigger array when needed, or to make an ArrayList and 'initialize' all the n values with a for loop.
What would be better to use?
Have a look at the implementation of ArrayList is does exactly what you suggest. It simply creates a bigger array whenever needed and copies all the entries form the small array.
This is quite efficient as long as the copy task must only be performed rarely and on not too big arrays. This is why you should always try to create an ArrayList with a size parameter that is about the size you expect that the list will grow to (or a bit bigger). This way you can minimize (or maybe avoid) the replacement of the internal array by a bigger one and all the effort it takes (the array copy).
P.s.
If your data is of an elementar data type you might want to avoid the overhead (memory and speed) of boxing into wrapper types. In this case ArrayList is not suitable for you and you might either implement a similar mechanism for the elementar data type you need it for or have a look at the www. I bed there are plenty implementations like this around there.
P.p.s
If you are unsure about the performance of different approaches, it is always a good idea to implement both and profile the performance for test data that are as close to your real data as possible.

How do I know whether to use an array or an arraylist?

What determines whether one should be used over the other?
I used to think that the deciding factor is whether you know the size of the things you want to store but I think there might be more to it than that.
Some more differences:
First and Major difference between Array and ArrayList in Java is that Array is a fixed length data structure while ArrayList is a variable length Collection class. You can not change length of Array once created in Java but ArrayList re-size itself when gets full depending upon capacity and load factor. Since ArrayList is internally backed by Array in Java, any resize operation in ArrayList will slow down performance as it involves creating new Array and copying content from old array to new array.
Another difference between Array and ArrayList in Java is that you can not use Generics along with Array, as Array instance knows about what kind of type it can hold and throws ArrayStoreException, if you try to store type which is not convertible into type of Array. ArrayList allows you to use Generics to ensure type-safety.
One more major difference between ArrayList and Array is that, you can not store primitives in ArrayList, it can only contain Objects. While Array can contain both primitives and Objects in Java. Though Autoboxing of Java 5 may give you an impression of storing primitives in ArrayList, it actually automatically converts primitives to Object.
Java provides add() method to insert element into ArrayList and you can simply use assignment operator to store element into Array e.g. In order to store Object to specified position.
One more difference on Array vs ArrayList is that you can create instance of ArrayList without specifying size, Java will create Array List with default size but its mandatory to provide size of Array while creating either directly or indirectly by initializing Array while creating it. By the way you can also initialize ArrayList while creating it.
Use array when you know the exact size of the collection and you don't expect to add/remove elements.
Use List (ArrayList) when you don't know the exact size of the collection and you expect to alter it at some point.
If you're using Java8, there is the Stream API, which helps to significantly reduce the boilerplate code when working with collections. This is another plus for ArrayList (and all Collections and Maps).
More info:
Arrays vs ArrayList in performance
Unless speed is critical (really critical, like every microsecond counts), use ArrayList whenever possible. It's so much easier to use, and that's usually the most important thing to consider.
Generally, I use ArrayList, not arrays, because they offer a lot of several methods that are very usefull. I think you can use array if performance is very important, in very special cases.
Array is fixed, ArrayList is growable.If the number of elements is fixed, use an array
Also one of the great benefits of collection implementations is they give you a lot of flexibility. So depending on your need, you can have a List behave as an ArrayList or as a LinkedList and so on. Also if you look at the Collection API, you'd see you have methods for almost everything you'd ever need to do.

java - what is the difference between a list and an arraylist [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is a List vs. an ArrayList?
Ive used both of them, but im just wondering what are the pros and cons between them? What are the major differences? And which one is better to use?
Thanks.
List is an interface implemented by ArrayList class. Another well-known implementation of the List is LinkedList.
ArrayList provides constant-time random access, while LinkedList provides constant time for non-sequential access. When you declare a variable that will hold an ArrayList, consider accessing it through an interface, like this:
List<ElementType> myList = new ArrayList<ElementType>();
This will let you swap in a different implementation without disturbing the rest of your code.
List merely describes the contract of what it means to be a list. As such, it is not a concrete implementation but merely an interface. A list can be implemented in a number of ways.
In particular, you have ArrayList, which internally keeps a dynamic array for storing all the elements in order. You also have LinkedList, which stores elements as a doubly linked list i.e. a sequence of nodes which keep references to the previous and next nodes.
Vector is another List, much like an ArrayList in that its implementation is based on a dynamic array; it's, however, a relic of the older versions of Java and is guaranteed to be thread-safe by being wholly synchronized. In practice, new Vector<T>() is more-or-less equivalent to Collections.synchronizedList(new ArrayList<T>()).
The reason for having a List is that a list can come implemented in a number of ways. That being said, often you want to have some sort of generic behavior that can be applicable to all Lists... see polymorphism.
A List is an interface, and an ArrayList is an implementation of that interface. An ArrayList is a List, and so are LinkedLists, Stacks, Vectors, etc.
the other posters already answered the "what" part of your question. Some considerations to think about when choosing between them.
An ArrayList uses an array behind the scenes. So accessing by index can be done in constant time. Adding can also be done in constant time, if the array has been allocated with enough space. However, when the space runs out, ArrayList will allocate a larger array and copy the old array values into the new one.
A LinkedList uses nodes that are chained together. Accessing by an index can potentially require walking the entire list (linear time). Inserting only requires creating a new node and adding it at the end (which could be constant time if a tail pointer is maintained).
So "which one is better" can depend on how you are using it. Truthfully, I've never measured performance differences between the two, but it's just something to consider.

What is the better Way to Store fixed no of data in Java? (Array vs ArrayList) [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I believe Array and ArrayList both are non-Synchronised;behave same in multiThreaded env.
And both are Index based. Only Adavantage is ArrayList has utility methods and flexible.
Apart from those Utility methods only to get and set fixed no of Objects which is best in java? Is there any overhead in using Arraylist than Array? Pls explain.
Let us consider Scenario like
1) 1,00,000 Objects to be stored.
2) 1,00,000 primitives to be stored
To be able to answer question on which data representation fits better, one needs to know many details like:
how many elements will be stored in the structure?
will the structure be mutable or immutable, that is, will the contents of the it change after initialization?
do you know the final size of your structure when you initialize it?
how will you access the elements? iterate over it? random access by index?
etc.
Regarding the array vs. arraylist: arraylist performance overhead is minimal and in most cases it is not significant. On the other hand, it is more flexible. see this thread Array or List in Java. Which is faster?
ArrayLists will have an ever so slightly higher overhead than an array. This is because an ArrayList is just a wrapper for an array with a few convenience methods added. Though if you know exactly how many elements you will ever have then ArrayList doesn't add much.
The biggest advantage of having an array over an ArrayList (at least in Java), is the cleaner syntax. eg.
myArray[0] = x;
// as opposed to
myList.set(0, x);
// personally I can never remember the order for the arguments and I have to check
Adding all the elements to another list
One possible advantage to ArrayLists is being able to easily add all the elements in an ArrayList to another list.
anotherList.addAll(myList);
However, the same can easily be accomplished by using the Collections util class.
Collections.addAll(anotherList, myArray);
Immutability
One problem is that arrays are mutable (element values can be changed), but you may only want to present a immutable view of your collection of elements to classes outside your own class. Here lists can be useful again.
List<E> readOnly = Collections.unmodifiableList(myList);
But in this case also Arrays can still easily be used to to back an immutable list.
List<E> readOnly = Collections.unmodifiableList(Arrays.toList(myArray));
Synchronized access
Finally, and most importantly, you can make use of the Collections class to make your Lists synchronized.
List<E> syncedList = Collections.synchronizedList(myList);
You could wrap your array in a list and make access synchronized, but then you'd still have to use access via the list, so there wouldn't be much point in having an array.
Final word - Personal preferences
In general though, the whole thing comes down to preference. What is your personal preference, do you prefer working with arrays or Lists? Personally I prefer lists because they work better with the rest of the collections API and making a generic Lists is easy, making generic arrays is a real pain.
List<E> list = new ArrayList<E>(); // easy
E[] array = new E[]; // compilation error
A ArrayList uses internally an Array. So yes, an ArrayList has a little bit of overhead, but it provides you with some convienent methods to access the elements in the list. It depends what you prefer.
If count of Objects is fixed, obviously Array is better solution. Because ArrayList uses array which can be created several times during adding.As javadoc says in array list function
Each ArrayList instance has a capacity. The capacity is the size of
the array used to store the elements in the list. It is always at
least as large as the list size. As elements are added to an
ArrayList, its capacity grows automatically.

Are there reasons to prefer Arrays over ArrayLists? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Benefits of arrays
Hey there,
are there any reasons to prefer Arrays (MyObject[]) over ArrayLists (List<MyObject>)? The only left place to use Arrays is for primitive data types (int, boolean, etc.). However I have no reasonable explanation for this, it just makes the code a little bit slimmer.
In general I use List in order to maintain a better flexibility. But are there reasons left to use real Arrays?
I would like to know,
best regards
I prefer to use Arrays over ArrayLists whenever I know I am only going to work with a fixed number of elements. My reasons are mostly subjective, but I'm listing them here anyway:
Using Collection classes for primitives is appreciably slower since they have to use autoboxing and wrappers.
I prefer the more straightforward [] syntax for accessing elements over ArrayList's get(). This really becomes more important when I need multidimensional arrays.
ArrayLists usually allocate about twice the memory you need now in advance so that you can append items very fast. So there is wastage if you are never going to add any more items.
(Possibly related to the previous point) I think ArrayList accesses are slower than plain arrays in general. The ArrayList implementation uses an underlying array, but all accesses have to go through the get(), set(), remove(), etc. methods which means it goes through more code than a simple array access. But I have not actually tested the difference so I may be wrong.
Having said that, I think the choice actually depends on what you need it for. If you need a fixed number of elements or if you are going to use multiple dimensions, I would suggest a plain array. But if you need a simple random access list and are going to be making a lot of inserts and removals to it, it just makes a lot more sense to use an Arraylist
Generally arrays have their problems, e.g. type safety:
Integer[] ints = new Integer[10];
Number[] nums = ints; //that shouldn't be allowed
nums[3] = Double.valueOf[3.14]; //Ouch!
They don't play well with collections, either. So generelly you should prefer Collections over arrays. There are just a few things where arrays may be more convenient. As you already say primitive types would be a reason (although you could consider using collection-like libs like Trove). If the array is hidden in an object and doesn't need to change its size, it's OK to use arrays, especially if you need all performance you can get (say 3D and 4D Vectors and Matrices for 3D graphics). Another reason for using arrays may be if your API has lots of varargs methods.
BTW: There is a cute trick using an array if you need mutable variables for anonymous classes:
public void f() {
final int[] a = new int[1];
new Thread(new Runnable() {
public void run() {
while(true) {
System.out.println(a[0]++);
}
}
}).start();
}
Note that you can't do this with an int variable, as it must be final.
I think that the main difference of an array and a list is, that an array has a fixed length. Once it's full, it's full. ArrayLists have a flexible length and do use arrays to be implemented. When the arrayList is out of capacity, the data gets copied to another array with a larger capacity (that's what I was taught once).
An array can still be used, if you have your data length fixed. Because arrays are pretty primitive, they don't have much methods to call and all. The advantage of using these arrays is not so big anymore, because the arrayLists are just good wrappers for what you want in Java or any other language.
I think you can even set a fixed capacity to arraylists nowadays, so even that advantage collapses.
So is there any reason to prefer them? No probably not, but it does make sure that you have just a little more space in your memory, because of the basic functionality. The arraylist is a pretty big wrapper and has a lot of flexibility, what you do not always want.
one for you:
sorting List (via j.u.Collections) are first transformed to [], then sorted (which clones the [] once again for the merge sort) and then put back to List.
You do understand that ArrayList has a backing Object[] under the cover.
Back in the day there was a case ArrayList.get was not inlined by -client hotspot compiler but now I think that's fixed. Thus, performance issue using ArrayList compared to Object[] is not so tough, the case cast to the appropriate type still costs a few clocks (but it should be 99.99% of the times predicted by the CPU); accessing the elements of the ArrayList may cost one more cache-miss more and so (or the 1st access mostly)
So it does depend what you do w/ your code in the end.
Edit
Forgot you can have atomic access to the elements of the array (i.e. CAS stuff), one impl is j.u.c.atomic.AtomicReferenceArray. It's not the most practical ones since it doesn't allow CAS of Objec[][] but Unsafe comes to the rescue.

Categories