Array and ArrayList [closed] - java

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.

Related

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.

Difference between List and Array

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.

Array vs array [] for 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?
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.
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.
My question is, which is better to use between these two, and is there a better way to accomplish the same result?
It depends on what you are trying to achieve:
If the number of elements in the array is known ahead of time, then an array type is a good fit. If not, a List type is (at least) more convenient to use.
The List interface offers a number of methods such as contains, insert, remove and so on that can save you coding ... if you need to do that sort of thing.
If properly used, an array type will use less space. The difference is particularly significant for arrays of primitive types where using a List means that the elements need to be represented using wrapper types (e.g. byte becomes Byte).
The Array class is not useful in this context, and neither is the Arrays class. The choice is between ArrayList (or some other List implementation class) and primitive arrays.
In terms of ease of use, the Array class is a lot easier to code.
The array[] is quite a problem in terms of the case that you need to know
the size of the list of objects beforehand.
Instead, you could use a HashMap. It is very efficient in search as well as sorting as
the entire process is carried out in terms of key values.
You could declare a HashMap as:
HashMap<String, Object> map = new HashMap<String, Object>();
For the Object you can use your class, and for key use the value which needs to be unique.

When to use a List over an Array in Java?

In Java, when would it be preferential to use a List rather than an Array?
I see the question as being the opposite-
When should you use an Array over a List?
Only you have a specific reason to do so (eg: Project Constraints, Memory Concerns (not really a good reason), etc.)
Lists are much easier to use (imo), and have much more functionality.
Note: You should also consider whether or not something like a Set, or another datastructure is a better fit than a List for what you are trying to do.
Each datastructure, and implmentation, has different pros/cons. Pick the ones that excel at the things that you need to do.
If you need get() to be O(1) for any item? Likely use an ArrayList, Need O(1) insert()? Possibly a Linked List. Need O(1) contains()? Possibly a Hashset.
TLDR: Each data structure is good at some things, and bad at others. Look at your objectives and choose the data structure that best fits the given problem.
Edit:
One thing not noted is that you're
better off declaring the variable as
its interface (i.e. List or Queue)
rather than its implementing class.
This way, you can change the
implementation at some later date
without changing anything else in the
code.
As an example:
List<String> myList = new ArrayList<String>();
vs
List<String> myList = new LinkedList<String>();
Note that myList is a List in both examples.
--R. Bemrose
Rules of thumb:
Use a List for reference types.
Use arrays for primitives.
If you have to deal with an API that is using arrays, it might be useful to use arrays. OTOH, it may be useful to enforce defensive copying with the type system by using Lists.
If you are doing a lot of List type operations on the sequence and it is not in a performance/memory critical section, then use List.
Low-level optimisations may use arrays. Expect nastiness with low-level optimisations.
Most people have answered it already.
There are almost no good reason to use an array instead of List. The main exception being the primitive array (like int[]). You cannot create a primitive list (must have List<Integer>).
The most important difference is that when using List you can decide what implementation will be used. The most obvious is to chose LinkedList or ArrayList.
I would like to point out in this answer that choosing the implementation gives you very fine grained control over the data that is simply not available to array:
You can prevent client from modifying your list by wrapping your list in a Collection.unmodifiableList
You can synchronize a list for multithreading using Collection.synchronizedList
You can create a fixed length queue with implementation of LinkedBlockingQueue
... etc
In any case, even if you don't want (now) any extra feature of the list. Just use an ArrayList and size it with the size of the array you would have created. It will use an Array in the back-end and the performance difference with a real array will be negligible. (except for primitive arrays)
Pretty much always prefer a list. Lists have much more functionality, particularly iterator support. You can convert a list to an array at any time with the toArray() method.
Always prefer lists.
Arrays when
Varargs for a method ( I guess you are forced to use Arrays here ).
When you want your collections to be covariant ( arrays of reference types are covariant ).
Performance critical code.
If you know how many things you'll be holding, you'll want an array. My screen is 1024x768, and a buffer of pixels for that isn't going to change in size ever during runtime.
If you know you'll need to access specific indexes (go get item #763!), use an array or array-backed list.
If you need to add or remove items from the group regularly, use a linked list.
In general, dealing with hardware, arrays, dealing with users, lists.
It depends on what kind of List.
It's better to use a LinkedList if you know you'll be inserting many elements in positions other than the end. LinkedList is not suitable for random access (getting the i'th element).
It's better to use an ArrayList if you don't know, in advance, how many elements there are going to be. The ArrayList correctly amortizes the cost of growing the backing array as you add more elements to it, and is suitable for random access once the elements are in place. An ArrayList can be efficiently sorted.
If you want the array of items to expand (i.e. if you don't know what the size of the list will be beforehand), a List will be beneficial. However, if you want performance, you would generally use an array.
In many cases the type of collection used is an implementation detail which shouldn't be exposed to the outside world. The more generic your returntype is the more flexibility you have changing the implementation afterwards.
Arrays (primitive type, ie. new int[10]) are not generic, you won't be able to change you implementation without an internal conversion or altering the client code. You might want to consider Iterable as a returntype.

Categories

Resources