Java arrays and objects - java

If arrays are treated as objects in Java and if we have a multidimensional array like an array of integer arrays then is it correct to say that this multidimensional array is also an array of objects?
I am kinda confused as I have read that arrays can hold only two types i.e. either primitives or references so if an array holds an array will it be correct to regard the same a array of objects?

Is it correct to say that this multidimensional array is also an array of objects?
Yes, that is correct. An array is an object. So, an array of arrays, is an array of objects.

Yes it is correct because arrays are objects

Arrays are not treated as objects, they are objects.

Multidimensional arrays are "arrays of arrays". You can get more information here http://www.ensta-paristech.fr/~diam/java/online/notes-java/data/arrays/arrays-2D-2.html
So it is also possible to create multi-dimensional arrays which are not square and so on

Yes, your reasoning is correct. When we say "array of objects" in Java we generally mean "array of references to objects", so when we have something like
int[][] x = ...;
then x is an array holding references to int[]s (i.e. int arrays).
From the JLS ยง10:
The component type of an array may itself be an array type. The components of such an array may contain references to subarrays. If, starting from any array type, one considers its component type, and then (if that is also an array type) the component type of that type, and so on, eventually one must reach a component type that is not an array type; this is called the element type of the original array, and the components at this level of the data structure are called the elements of the original array.
There are some situations in which an element of an array can be an array: if the element type is Object or Cloneable or java.io.Serializable, then some or all of the elements may be arrays, because any array object can be assigned to any variable of these types.

Related

How do I add to the first empty index in a generic type array?

I am making an ArrayList class from scratch using generic types, and one of the methods I need to include is one that adds an element to the first empty index in the arrayList.
I initialized the array with T[] list = (T[]) new Comparable[size];
Say size = 10; and indices 0-3 are filled with various Objects. How would I locate index 4 as the first empty index? Are generic arrays initialized with nulls or something else?
Thank you
There are really 2 types of arrays in Java: Primitive arrays and object arrays. Hint: Generics are objects.
The elements of primitive arrays are initialized to 0, or false for a boolean[], and the elements of object arrays are initialized to null.
Those are the exact same default values that are also assigned to fields of the given types, e.g. a field like this will be null by default:
private Comparable<Foo> comparable;

Why is an ArrayList of ArrayLists not multidimensional?

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.

How to find Array type and its dimensions for a multidimensional Array for an Object reference

I have a Object reference which may or may not be a array.It can be a multidimensional array.I want to find the component type and length of the array dimensions.
What I have tried so far is get the runtime class type of the Object from object.getClass() and then count the number of '['.But again I would not know the dimensions of the array.
I want to know if there can be cleaner way.
PS:- I have a plain Object reference
Use Class#getComponentType().
Object ref = new int[2][3][4];
System.out.println(ref.getClass().getComponentType());
It will return the Class object for the array type, if it is an array. Otherwise it will return null. You can keep doing this for multidimensional arrays until it returns null.
You can use Array#getLength(Object) to find the length of each individual dimension.
System.out.println(Array.getLength(ref));

Primitive arrays in Java collections

When I implement a Collection using generics that holds primitive arrays within Java what is actually stored within the array? Using generics to define collections means that I can only store an Object and if I were to do ArrayList<Integer> I can add an int but this is autoboxed into Integer.
If I were to define ArrayList<int[]> its perfectly legal as arrays are objects. I'm unsure though if what I actually end up with stored in the collection is Integer[] as the compiler performs some transformations and will use autoboxing to add to the array or if I can store int[] and the collection will store the primitive array as the array itself is an object.
ArrayList<int[]> will store arrays of primitives. There will be no autoboxing involved.
In Java, an array of any type -- primitive or not -- is an object and is therefore compatible with generics.
It is even possible to inadvertently end up with a container of int[], as illustrated by this fun question from yesterday: Java containsAll does not return true when given lists
int[] never be boxed to Integer[].Arrays are always reference types, so no boxing is required.
Java always tackle Arrays as a object either it is a primitive array or Object array.Here is a little detail about arrays of primitives and objects.For further detail please see Arrays of Primitive Values and objects.I also suggest you to see this question Java: Array of primitive data types does not autobox

How are arrays implemented in java?

Arrays are implemented as objects in java right? If so, where could I look at the source code for the array class. I am wondering if the length variable in arrays is defined as a constant and if so why it isn't in all capital letters LENGTH to make the code more understandable.
Although arrays are Objects in the sense that they inherit java.lang.Object, the classes are created dynamically as a special feature of the language. They are not defined in source code.
Consider this array:
MySpecialCustomObject[] array;
There is no such source code for that. You have created it in code dynamically.
The reason why length is in lower case and a field is really about the fact that the later Java coding standards didn't exist at the time this was developed. If an array was being developed today, it would probably be a method: getLength().
Length is a final field defined at object construction, it isn't a constant, so some coding standards would not want that to be in upper case. However in general in Java today everything is generally either done as a constant in upper case or marked private with a public getter method, even if it is final.
For every Array we declare, corresponding classes are there in Java but it's not available to us.You can see the classes by using getClass().getName()
int[] arr=new int[10];
System.out.println(arr.getClass().getName());
Output : [I
where "[" represents one dimension array and "I" represents Integer.
Similarly, we can have
[F for one-dimensional float arrays
[Z for one-dimensional boolean arrays
[J for one-dimensional long arrays
[[I for two-dimensional int arrays
and so on.
Implementing array in Java requires access to memory location or do pointer arithmetic. As Java does not let you to allocate memory, it does the Arrays implementation for you. Java language provides that implementation.
We can say that An array is a container that holds a fixed length of data of single data type.
eg.
int[] MyArray = new int[101]; // allocates memory for 101 integers, Range from 0 to 100.
and for multidimensional
String[][] names = {{"FirstName", "LastName"},{"Kaji", "Islam"},...};
and for character array
char[] ch={'a','b'....};

Categories