Why is an ArrayList of ArrayLists not multidimensional? - java

I recently appeared for an interview in which the interviewer asked me a question regarding Arrays and ArrayList.
He asked me if an array of arrays can be multidimensional, then why is an ArrayList of ArrayList's not multidimensional?
For example:
// Multidimensional
int[][] array = new int[m][n];
// Not multidimensional
ArrayList<ArrayList<Integer>> seq = new ArrayList<ArrayList<Integer>>();
Can anyone help me to understand this?

Cay S. Horstmann has stated within his book Core Java for the impatient:
There are no two-dimensional array lists in Java, but you can declare a
variable of type ArrayList<ArrayList<Integer>> and build up the rows
yourself.
due to the fact that ArrayLists can expand and shrink and become jagged rather than multi-dimensional, one could say it is not a two-dimensional array, multi-dimensional meaning fixed rows and columns, hence why I have also stated within the comments Java doesn't have true multi-dimensional arrays but this is outside the scope of your question.
if you're curious as to why I said Java doesn't have true multi-dimensional arrays have a read at the differences between a multidimensional array and an array of arrays in C#?
Just to make my answer clearer regarding whether Java has true multi-dimensional arrays or not, I did not say java doesn't have multi-dimensional arrays, I said Java doesn't have true multi-dimensional arrays and as expect the JLS has stated:
A multidimensional array need not have arrays of the same length at
each level.

For the same reason the shopping bag I put all my spare shopping bags into is not a multidimensional shopping bag.
If I put a nut in one bag then put that bag in another bag, I have to perform two operations to get the nut.
If I instead put the nut in a two dimensional component tray, I can perform one operation to access it using two indices:
source
Similarly, there is a fundamental difference between a list of lists ( or array of arrays ) and a true two dimensional array - a single operation taking two indices is used to access the elements in a two dimensional array, two operations each taking one index are used to access the elements in a list of lists.
An ArrayList has a single index, so it has a rank of 1. A two dimensional array has two indices, its rank is 2.
note: by 'two dimensional array' I am not referring to a Java array of (references to) arrays, but a two dimensional array as found in other languages such as FORTRAN. Java does not have multidimensional arrays. If your interviewer was specifically referring to Java 'arrays of arrays' then I would disagree with them, as Java's int[][] defines an array of references to arrays of integers, and that requires two dereferencing operations to access the elements. An array of arrays in C for example supports access with a single dereferencing operation so is closer to the multidimensional case.

I'm going to go out on a limb here and answer this one, however there is no correct answer for this broad question.
We first have to ask, what makes an array multidimensional?
I'm going to assume that your interviewer considers a multidimensional array one with a fixed size (as you've shown in your question), where it cannot be considered "jagged". According to Microsoft, a jagged array in C# is as follows:
The elements of a jagged array can be of different dimensions and sizes.
In Java, a multidimensional array is simply an array, where each element is also an array. These arrays must be defined with a fixed size in order for elements to be indexed within them, but jagged arrays can be of different sizes, as stated above.
An ArrayList is backed by an array; however, the array expands when a certain number of elements are added to it. For this reason, the ArrayList could become jagged, and could be considered not to be multidimensional any longer.
Edit: After rereading everything over a few times, I'm sure that your interviewer was just trying to confuse you. It honestly doesn't make sense for one data type (an array) to be multidimensional, and another data type (an ArrayList that uses an array) to not be multidimensional.

Looking at it from the other side: you can use lists in the very same way as "multi dimensional" arrays. You only have to replace array[row][column] with someList.get(row).get(column)!
And in the end, java arrays are implemented in similar ways: a two dim matrix is also just a one dim array of one dim arrays! In other words: the difference is more on the surface, not rooted in deep conceptual reasons!
And to be really precise: the Java type system allows you to put down Object[][] so in that sense, it knows that type of Object[][]; but as said, in reality, there are no multi-dimensional arrays; as Java sees that "two dim" thing as an array of references to arrays!
On the other hand: there is a certain notion of "multi dimensional arrays", as for example the JVM specification explicitly mentions:
The first operand of the multianewarray instruction is the run-time constant pool index to the array class type to be created. The second is the number of dimensions of that array type to actually create. The multianewarray instruction can be used to create all the dimensions of the type, as the code for create3DArray shows. Note that the multidimensional array is just an object and so is loaded and returned by an aload_1 and areturn instruction, respectively.

The interviewer's claim is nonsensical.
One can argue, as you see on this page, that Java does not have true multidimensional arrays, in which case it does not have multidimensional ArrayLists either. On the other hand, it certainly allows you to represent multidimensional structures via arrays and ArrayLists in the same way.
To define a major distinction between the two is fairly arbitrary and pointless.
Possibly the interviewer was just trying to start a technical debate, to test your ability to explain the details.

An ArrayList is an implementation of List. It's a List that is implemented using arrays. The usage of arrays is an implementation detail. The list interface doesn't support the concept of multi-dimensional lists therefore you wouldn't expect ArrayList to either. Further it isn't addressed as a use case of a traditional list data structure.
Arrays support multi-dimensionality because it's a language feature of Java.

Because it isn't dimensional at all. It is an object with an API. Any appearance of multi-dimensionality is provided by its API, but it is purely in the eye of the beholder. An array on the other hand is dimensional, and can therefore be multidimensional too.

Related

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.

How are Java Nested Arrays implemented in memory?

Consider a nested array in java. Does the top level of the array contain references to the inner arrays, or does the memory actually contain the inner arrays themselves?
If you need an illustration, assume I have access to a reverse method, which will reverse an array in place by doing multiple swaps. If I call reverse on the top-level of an M*N nested array, what will that method simply swap references around (an O(m) operation), or will it be swapping entire rows around (an O(m*n) operation)?
In a word references. Arrays themselves are likely to be contiguous blocks, but it's unlikely that the Objects the elements refer to are.
This article sums it up nicely http://java.dzone.com/articles/what-does-java-array-look
I believe you can find the answer in most introductory Java book (although it may be not that obvious).
In Java, nested/multi-dimension array is not a continuous block. It is simply an array of "reference to array".

Comparing functionality between Vectors and Arrays in Java

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

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.

When is an ArrayList preferable to an array in Java?

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,

Categories