Difference between List and Array - java

Possible Duplicate:
Primitive Array vs ArrayList
What is the difference between List and Array in java? or the difference between Array and Vector!

In general (and in Java) an array is a data structure generally consisting of sequential memory storing a collection of objects.
List is an interface in Java, which means that it may have multiple implementations. One of these implementations is ArrayList, which is a class that implements the behavior of the List interface using arrays as the data structure.
There are a number of other classes that implement the List interface. One easy way to take a look at them is by viewing the Javadoc for List: http://docs.oracle.com/javase/6/docs/api/java/util/List.html
On that page, you'll see "all known implementing classes," which are all of the kinds of lists in Java.

Related

Array and ArrayList [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I have some questions about Array and ArrayList. I have searched here and could not find precisely the answers i am looking for.
I understand Arrays and ArrayList are part of java.util. So when I create and Array or ArrayList am I creating objects and instances?
Why must the java.util.ArraList be imported to create an ArrayList object but there is no need to import java.util.Arrays to create and Array object?
Why are the methods of Array called in a different manner than those of ArrayList? Is it because the methods of Arrays class are all static?
Why it is said that the performance of using and Array is faster than the performance of using an ArrayList?
I understand that to iterate values in an Array a for loop could be used. What about to iterate values in ArrayList - I understand that a for loop can also be used but in the Internet it is said that I could use an iterator, what would be this iterator?
Can an Array be multidimensional if it is storing objects?
If I am working with primitive data then i understand they should all be stored in an array, since ArrayList cannot contain primitive data types. But if I am working only with objects, should I choose to work with Array or ArrayList?
Yes, when you create an array or ArrayList you are creating an instance/object.
Packages are like directories containing Class definitions (e.g. the java.util package contains the ArrayList class). All classes within a package have a unique name. But class names can be reused in other packages. So, there is actually more than 1 ArrayList class possible.
So, that's why the java compiler always needs to know the full name of the class.
So, when you are creating an ArrayList you want the compiler to know that you are creating a java.util.ArrayList. You could actually specify that during your object creation:
java.util.ArrayList list = new java.util.ArrayList();
But that's really verbose. It's annoying that you would have to repeat this full name all the time. That's what the import statements are for. By specifying an import java.util.ArrayList you are telling the compiler that all references to ArrayList are in fact of type java.util.ArrayList.
Arrays are really special classes. They are not primitives, but there's a lot happening underneath the hood of the java virtual machine and compiler. Honestly, I don't want to explain too much about this, because it would just confuse you.
But in short, java uses a dedicated class for each type of array. So, there's a int[] class, a long[] class, an Object[] class etc.
Honestly the performance of an array is not better than the one of an ArrayList. Both have their strong points.
An Iterator is something that was invented before for-each iterations were introduced in java. You can only use iterator for collections that implement the Iterable interface. (Again, not the case for arrays). One of the advantages of iterators, is that you can remove objects from a list while iterating (ie using the iterator.remove() method)
Sure, an array can be multidimensional, even if it stores objects. And indeed an ArrayList cannot contain primitive types.
I usually prefer the use of an ArrayList. One of the main advantages of an ArrayList, is that it automatically resizes when it's capacity is exceeded. That's not the case for an array.
On the other hand, if you know the exact length of your list, then an array will use less memory.
Just to be complete: there is also an Arrays class which contains the convenience methods that are missing on the array instances. Indeed, those methods are strictly static methods.
In the simplest manner, hand-waving past the details:
An array (note the small-a name) is a fixed size aggregate type; it is not something that can be classed. An ArrayList is part of the Collections framework. See the Javadocs for details on what this collection offers.
java.util.Arrays is a convenience class that provides static methods useful for manipulating arrays. Since they are static, there is no direct instantiation required or allowed.
Your other questions need to be adjusted once you get past these fundamentals.
The ArrayList is one of the collections available in the Java collections library. You create an ArrayList object which lets you manage a sequence of items. On the other hand, Arrays is a collection of utility functions that operate on arrays. You create a new array by doing something like new int[10].
You construct an ArrayList with new ArrayList(), thus you must import it. The Arrays class has nothing to do with creating arrays and is thus not required.
Arrays and ArrayList are entirely different. One is just a collection of functions (which are not methods of the array) and you cannot create an instance of Arrays. The methods of ArrayList directly operate on the ArrayList.
An array provides direct access to array storage and holds values of any type (primitives and object references), while an ArrayList van only hold object references. For object references, there is no real speed difference, but for primitives, the values must be put into and taken out of an object "box", which is substantially slower.
An iterator is an object which implements traversal of a collection, letting you get the next item (next) and allows you to ask if there are any more (hasNext) in the most efficient way possible for the type of collection. Iterators are also used in loops, but are safer because you don't have to manage indexes yourself.
Yes. An ArrayList is also an object, so a multidimensional ArrayList is just an ArrayList which holds ArrayLists.
If working with arrays of objects, always use ArrayList. It is far easier to work with (for example, if you add to an ArrayList, it will seamlessly reallocate the array) and it is safer. With generics, you can guarantee the right type of objects are added. With arrays, you can cast String[] to Object[], but an ArrayList<String> cannot be cast to ArrayList, making it impossible to put aDoubleinto aString` array.

Properly defining collection in java

While reading collections in java and browsing some of the questions on stackoverflow, I came across this question:
Method for adding Objects into a fixed collection(Array) in Java
Here an Array has been referred to as fixed collection. Conceptually, is it legitimate to call an Array a 'fixed collection' or is it a self-contradicting phrase?
A collection framework is basically a framework to store and retrieve the collection of java objects efficiently.
A very good link about overview of data structure is here
As per this link
There are fourteen collection interfaces. The most basic interface is Collection. These interfaces extend Collection: Set, List, SortedSet, NavigableSet, Queue, Deque,
BlockingQueue and BlockingDeque.
The other collection interfaces, Map, SortedMap, NavigableMap, ConcurrentMap and ConcurrentNavigableMap do not extend Collection, as they represent mappings
rather than true collections. However, these interfaces contain collection-view operations, which allow them to be manipulated as collections.
Now coming back to array its not part of collection framework but logically its collection as it can store collection of objects. Even if you develop your custom class that can store bunch of objects you can logically call it collection object.
An array is a collection if you define a collection as a container of elements.
Of course an array does not implement the Collection interface, but calling Arrays.asList(arr) on an array actually gives you a fixed size List view of that array, so you can say an array is almost equivalent to a fixed length random access List (A List is a Collection).

Data Structures in Java & Python and their implementations: Lists, Arrays, Tuples

I know Java and also recently started learning Python. At one point I understood that I need to take a pause and clarify all questions related to Data Structures, especially Lists, Arrays and Tuples. Could you please correct me if I am wrong in any of the following:
Originally, according to Data Structures standards, Lists do not
support any kind of indexation. The only way to get access to the
element is through iterations (next method).
In Java there is actually a way to get access to elements by index (i.e. get(index) method), but even if you use these index-related methods it is still iterating from the first element (or more specifically its reference)
There is a way in Python to access to Lists elements as we work with arrays in Java, using list[index] syntax, but in reality, even though this data type is called "lists", we do have an array of references in the background and when we refer to the third element, for example, we are referring directly to the 3 element in array to get reference without iteration from the first one (I am pretty sure that I am wrong over here)
Tuples are implemented in the same way as Lists in Python. The only difference is that they are immutable. But it is still something closer to lists than arrays, because elements are not located contiguously in memory.
There are no arrays as in Python
In Data Structure theory, when we are creating an array, it uses only a reference to the first cell of memory, and then iterates to the # of element that we specified as index. The main difference between Lists and Arrays is that all elements are located contiguously in memory, that's why we are winning in performance aspect.
I am pretty sure that I am wrong somewhere. Could you correct me please?
Thanks
Most of that is wrong.
The list abstract data type is an ordered sequence of elements, allowing duplicates. There are many ways to implement this data type, particularly as a linked list, but most programming languages use dynamically resized arrays.
Even linked lists may support indexing. There is no way for the implementation to skip directly to the n'th element, but it can just follow links to get there.
Java's List type does not specify an implementation, only an interface. The ArrayList type is a List implemented with a dynamic array; the Linkedlist is exactly what the name says.
Python's lists are implemented with dynamically resized arrays. Python's tuples are implemented with fixed-size arrays.
There are actually two Python types commonly referred to as arrays, not counting the common newbie usage of "array" to refer to Python lists. There are the arrays provided by the array module, and there are NumPy's ndarrays.
When you index an array, the implementation does not iterate from the location of the first element to the n'th. It adds an offset to the address of the array to skip to the element directly, without iterating.

how does an ArrayList compare to a dynamic array

Is an ArrayList is just the interface for a dynamic array? Or are they the same thing?
like: ArrayList corresponds to dynamic array, HashMap corresponds to Map ?
except I don't see any Java API for something like a dynamic array, unless it is ArrayList?
Yes. In short. A longer explanation is that an ArrayList is a collection that uses arrays for storage, rather than a linked list, doubly linked list or similar. This means that it gives all the benefits of using an Array, whilst Java looks after the mechanics of sizing the Array for you (dynamically).
I seem to remember that the initial array is created with a default maximum size (which can be specified by the user). Should the collection run out of space, then a larger array is created and the contents of the original array copied into the new one. The increment in size is set to prevent this happening too often, as the operation is fairly costly.
Java also offers the Vector collection which is similar, but is also thread safe, see: What are the differences between ArrayList and Vector?.
ArrayList is the resizable-array implementation of the List interface.
So that's probably what you are looking for if you need a dynamic array.
ArrayList is not a dynamic array, it's not an array type dynamic or not, it's just one of the implementations of the List interface. Understand the difference between classes and interfaces. On the other hand arrays are container objects with the fixed size.
If in the dynamic sense you mean an array which can change in size then a List is an interface for a dynamic array. It is named ArrayList because it uses an array internally that's all.
Your analogy does not fit in the java collections framework since you can say that an ArrayList is a dynamic array but Map (or HashMap for that matter) does not have a "primitive" counterpart.
If by 'dynamic array' you mean an array in C++, then all arrays in Java are dynamic and stored on heap. ArrayList is a resizable wrapper for it. It also provides simple consistency checks - i.e. that you don't modify your array from outside during iteration.

Vector-Java equivalent in PHP?

Is there a:
1> Vector(Java) class
2> ListIterator
3> Single Linkedlist
equivalent available in PHP?
The short answer is:
Array
Array
Array
PHP arrays are powerful constructs that are can be used as arrays, lists, hashes, queues and stacks (which may all be different types in other languages) all at the same time.
If you need more control over the behaviour of an array-like construct, there are interfaces and classes in Standard PHP Library (SPL) you can implenet/use/extend.
1) Any PHP array can be considered and used as a Vector (since by definition Vector is just an array that can grow in size and PHP doesn't require to specify array size). As java documents it,
public class Vector
extends AbstractList
implements List, RandomAccess, Cloneable, Serializable
PHP array fulfills all there requirements.
2) There is an Iterator if you insist on it, but in general it is much more common to use loops for array traversing (just like you don't really iterate arrays in Java with Iterator, do you?)
3) There is no list implementations in PHP in general (well, I bet internally arrays are implemented as a list/hashmap, but that's only internally). You can go with one of two options. Either use array (do you see a pattern here - arrays FTW!) if you are only interested in sequential ordering of items (you get random access as a bonus), or you can implement your own completely-OO list with 2 small classes (I'd call them List and ListCell)
Addition to part 3: Don't worry about insertions or deletions in the middle of the list, as those may be achieved with array_slice and array_splice. Insertion and deletion may not be O(1) timewise, but since in the list you would also need O(n) time for locating the place to insert in the list, I thing the options are comparable.

Categories

Resources