I've been thinking about this one for a long time. What is the difference between Vectors and Arrays? I know they do similar things, if not exact.
String Array
String[] array = new String[4];
String Vector
Vector<String> vector = new Vector<String>(4);
It seems kind of redundant to me why there would be both arrays and vectors. Are there any advantages or disadvantages to using one or the other?
Vectors are resizable. Arrays are not.
The difference is that 'Vector' is an extension by programmers, whereas an array is a built-in function of the language itself.
You can edit how the Vector behaves (by editing its source code), whereas an array is defined by the compiler.
And obviously, Vectors can be potentially sized (depending on implementation). Arrays are static and cannot be resized - you have to recreate it and copy the data over.
Vector is synchronized. Arrays are not(?).
Array cannot be re-sized, while Vectors can.
Vector uses Arrays internally. The main advantage of a Vector compared to an Array is its automatical increase of capacity. An Array keeps its size once created, a Vector does not
It seems kind of redundant to me why there would be both arrays and
vectors
For one, Vectors can be resized. If you declare an array of size 10, you are left with 10 always, unless you copy the contents to another larger sized array. Methods of Vector are synchronized.
Vectors are part of the collections framework. Vector is a List. There are other lists, ArrayLists, LinkedLists etc with specific features. There are Sets and Maps. All of them hold "lists" of items, but each of them give specific advantages in specific situations.
You might want to read about java collections.
Vectors will automatically resize for you to accommodate as many entries as you want in them. An array is fixed in size, and will give you an OutOfBounds exception when you try to add more than you allocated.
When you provide the size for a vector, that's just the original size it starts with. It'll automatically grow/shrink as necessary.
1- Vectors are resize-able, arrays are not
2- Vectors are responsible for memory allocate and release, arrays are not. This makes vectors safer to use than arrays.
3- Vectors have a good performance on their implemented functions, which you may not reach by your own programming with arrays.
4- Finally I think it's wiser to use vectors, most of the times.
An array is a basic java data structure, whose size is fixed when defined.
A Vector is part of the Java Collections Framework, and contrary to your beliefs, or not even close to the same thing as an array. Among many other things, Vectors are resizable and can interact with other collections.
Java array types are not necessary. They actually create a lot of problems. Avoid them if you can.
We could do better to replace them with a standard class Array<T>. Some new post-Java languages are taking this approach.
(History alert) In the old days, Java didn't have generics, a non-generic collection class would suck to use (with lots of castings). Then array types were really poor man's generics because they carry element type info. That's why many methods return arrays, instead of List.
I think the above suggestion is not good. Check this link to get brief idea.
Difference b/w Array and Vector
Vectors help to insert and delete elements easily while arrays helps to sort and access elements with ease.
Vectors can hold different type of elements
Arrays only the type defined when forming them
You can use array list which is some what similar to vector and provided much better features
Related
I am confusing to decide which list has less time complexity since adding items. Does list have less bigO than 2D array?
I wanna use it to represent an undirected and unweighted graph with about 1000 vertexes. It is used to store vertexes.
List<Integer> list
VS.
int[][] list2
You would only care if you are talking about huge numbers of elements within your lists/arrays.
The classes provided by collections framework; like ArrayList do add a certain performance price tag; compared to plain old arrays. So, when you have to compute something on 10 million numbers; you might be better of using double[] instead of ArrayList.
But for most other use cases, collections simply provide a much richer interface; this means it is much easier to "optimize" code for readability and maintainability if you avoid using arrays and instead turn to some collection class. And in real world, those properties are actually much more important that the runtime cost of using these more advanced abstraction layers.
And just to be sure to actually answer the question: I think the "O cost" of ArrayList is the same as for arrays; as in big-O of ArrayList would be some "xn"; and array would be "yn"; with x being bigger than y.
So, from a conceptual point, they are within the same class; but from a practical stand point lists are more expensive.
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.
What is the difference between using a Guava Table implementation and a 2D array if I know the size of the array beforehand?
Is one more efficient than the other? How?
Would it make a difference in running time?
The most obvious and crucial difference is that an array is always indexed, with ints, whereas a Table can be indexed with arbitrary objects.
Consider the Table Example from the Guava site:
Table<Vertex, Vertex, Double> weightedGraph = HashBasedTable.create();
weightedGraph.put(v1, v2, 4);
...
The indexing here happens via Vertex objects. If you wanted to do the same with an array, you would have to add some getIndex method to the Vertex class, and accesss the array like this
double array[][] = new double[4][5];
array[v1.getIndex()][v2.getIndex()] = 4;
This is inconvenient and particularly hard to maintain - especially, when the indices may change (or when vertices have to be added/removed, although you mentioned that this is not the case for you).
Additionally, the Guava table allows obtaining rows or columns as separate entities. In a 2D array, you can always access either one row or one column of the array - depending on how you interpret the 2 dimensions of the array. The table allows accessing both, each in form of a Map.
Concerning the performance: There will be cases where you'll have a noticable difference in performance. Particularly when you have a large 2D array of primitive types (int, double etc), and the alternative would be a large table with the corresponding reference types (Integer, Double etc). But again, this will only be noticable when the array/table is really large.
Additionally to what Marco13 said, read this: https://stackoverflow.com/a/6105705/1273080.
Collections are better than object arrays in basically every way
imaginable.
The same applies here. A 2D array is a low-level tool that might be needed when you need some high-performance structure for primitives. However, arrays have no meaningful methods, no behaviour, no nothing, and therefore are usually an underlying data structure in classes that add some behaviour to them. Do this with a 2D fixed-size array and you'll end up with ... a Guava-esque Table.
Also, a Table can be a 2D-array, or a Map<R, Map<C, V>>, in the future we might also have resizable Table implementations - all within one interface.
Regarding the performance - you should almost always go for the more high-level approach to get code as readable and clear as possible, then measure the performance and only if it's problematic, go for different approaches.
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.
When should I use an ArrayList in Java, and when should I use an array?
Some differences:
Arrays are immutable in their size, you cannot easly remove and element and remove the hole whereas using an ArrayList is straightforward
Arrays are fast (handled directly by the JVM as special objects) than an ArrayList and requires less memory
Arrays have a nice syntax for accessing elements (e.g. a[i] vs a.get(i))
Arrays don't play well with generics (e.g. you cannot create a generic array)
Arrays cannot be easly wrapped as ArrayList (e.g. Collections utils like checkedList, synchronizedList and unmodifiableList)
declaring the ArrayList as List you can easly swap implementation with a LinkedList when you need; this imho is the best advantage over plain arrays
Array's toString, equals and hashCode are weird and error-prone, you must use Arrays class utilities
Another couple of points:
You may want to consider using an array to represent more than one dimension (e.g. matrix).
Arrays can be used to store primitives and hence offer a more compact representation of your data than using an ArrayList.
ArrayLists are useful when you don't know in advance the number of elements you will need. Simple Example: you are reading a text file and builing a list of all the words you find. You can just keep adding to your array list, it will grow.
Arrays you need to pre-declare their size.
It's not only about the fact that arrays need to grow, a collection is easier to deal with.
Sometimes arrays are fine, when you just need to iterate over elements, read-only. However, most of the time you want to use methods like contains, etc.
You can't create generic arrays so it 'might' or might not bother you.
When in doubt, use Collections, it will make people that use your API love you :-). If you only provide them with arrays, the first lines of code that they'll write is :
Arrays.asList(thatGuyArray);
The List interface, of which ArrayList is an implementation in the Java Collections Framework is much richer then what a plain Java array has to offer. Due to the relatively widespread support of the collection framework throughout Java and 3rd party libraries, using an ArrayList instead of an array makes sense in general. I'd only use arrays if there is really need for them:
They are required by some other interface I'm calling
Profiling shows a bottleneck in a situation where array access can yield a significant speedup over list access
Situations where an array feels more natural such as buffers of raw data as in
byte[] buffer = new byte[0x400]; // allocate 1k byte buffer
You can always get an array representation of your ArrayList if you need one:
Foo[] bar = fooList.toArray(new Foo[fooList.size()])
It is a common failure pattern that methods return a reference to a private array member (field) of a class. This breaks the class' encapsulation as outsiders gain mutable access to the class' private state. Consequently you would need to always clone the array and return a reference to the cloned array. With an ArrayList you can use...
return Collections.unmodifiableList(privateListMember);
... in order to return a wrapper that protects the actual list object. Of course you need to make sure that the objects in the list are immutable too, but that also holds for a (cloned) array of mutable objects.
As per Nick Holt's comment, you shouldn't expose the fact that a List is an ArrayList anywhere:
private List<Foo> fooList = new ArrayList<Foo>();
public List<Foo> getFooList() {
return Collections.unmodifiableList(fooList);
}
An array has to be declared with a fixed size therefore you need to know the number of elements in advance.
An ArrayList is preferable when you don't know how many elements you will need in advance as it can grow as desired.
An ArrayList may also be preferable if you need to perform operations that are available in its API that would required manual implementation for an array. (e.g. indexOf)
When you want to change its size by adding or removing elements.
When you want to pass it to something that wants a Collection or Iterable (although you can use Arrays.asList(a) to make an array, a, look like a List).
I would say the default presumption should be to use an ArrayList unless you have a specific need, simply because it keeps your code more flexible and less error prone. No need to expand the declaration size when you add an extra element 500 lines of code away, etc. And reference the List interface, so you can replace the Array list with a LinkedList or a CopyOnWriteArrayList or any other list implementation that may help a situation without having to change a lot of code.
That being said, arrays have some properties that you just won't get out of a list. One is a defined size with null elements. This can be useful if you don't want to keep things in a sequential order. For example a tic-tac-toe game.
Arrays can be multi-dimensional. ArrayLists cannot.
Arrays can deal with primitives, something an ArrayList cannot (although there are third party collection classes that wrap primitives, they aren't part of the standard collections API).
G'day,
A couple of points that people seem to have missed so far.
an array can only contain one type of object whereas an ArrayList is a container that can contain a mixture of object types, it's heterogeneous,
an array must declare the type of its contents when the array itself is declared. An ArrayList doesn't have to declare the type of its contents when the ArrayList is declared,
you must insert an item into a specific location in an array. Adding to an ArrayList is done by means of the add() method on the container, and
objects are stored in an array and retain their type because of the way the array can only store objects of a particular type. Objects are stored in an ArrayList by means of the superclass type Object.
Edit: Ooop. Regarding the last point on the list, I forgot the special case where you have an array of Objects then these arrays can also contain any type of object. Thanks for the comment, Yishai! (-:
HTH
cheers,