Is an array a primitive type or an object (or something else entirely)?
There is a class for every array type, so there's a class for int[]
, there's a class for Foo[]
. These classes are created by JVM. You can access them by int[].class
, Foo[].class
. The direct super class of these classes are Object.class
public static void main(String[] args)
{
test(int[].class);
test(String[].class);
}
static void test(Class clazz)
{
System.out.println(clazz.getName());
System.out.println(clazz.getSuperclass());
for(Class face : clazz.getInterfaces())
System.out.println(face);
}
There's also a compile-time subtyping rule, if A
is subtype of B
, A[]
is subtype of B[]
.
java primitive type array object or not?
In Java you only have primitive or references to objects.*
int[] arr = { 1, 2 };
int i = arr[0];
assert arr instanceof Object; // true
arr
is a reference to an array which has int
as a element.
how it was achieved?
int[]
has it's own class int[].class
and your arr
is an instance of that class.
It was sth like int=>Integer, or int[]=>Integer[] or something else?
Integer
is not related at all. to convert an int[]
into an Integer[]
you have to create a new array and copy every element one by one.
And by the way, where it resides? In heap or in stack?
You can assume all objects are on the heap. Java 8 can place some objects on the stack using Escape Analysis, however I don't believe it can do this for array types.
*
the only other type is void
which is neither a primitive nor a reference. It has a wrapper Void
but you can't have a field or parameter of type void
.
Is java's array primitive type?
Is java's array “primitive type”?
No. Java's array is a reference type. You can see the java.lang.reflect.Array
class for insight into how it works internally. For example,
int[] i = { 1, 2, 3 };
Object v = i;
System.out.println(v.getClass());
System.out.println(Array.get(v, 1));
Outputs
class [I
2
Do the elements of a one-dimensional array have to be of primitive data type in Java?
An array can store elements of any type - a primitive int
or long
or float
, a wrapper Integer
, an object like String
, Person
, Animal
, etc.
You must understand that any Array data structure is meant to be stored as contiguous block of memory, be it of anything, but of the same data type.
- With primitive types, it is the contiguous block of actual values,
i.e., int array will have each int occupy 4 bytes, array of long
will have each occupy 8 bytes, and so on. - With an array of objects (String, Person, Animal) the array will store the reference variable (this is not a pointer like in C++) to all of those objects and those references will be in contiguous block.
Like if you have Person p1 = new Person()
and Person p2 = new Person()
and store in an array Person[] arr = {p1, p2}
.
The arr will have the references p1 and p2 stored in the memory and when you traverse the array you can reach the actual Person object, which in itself can be a mixture of many String or int values (like id, name, address, etc). So this still gives you the efficiency of an array.
This doesn't mean that arr becomes multi dimensional in any way.
You can read about this at many other places in more detail and get back to your teacher.
Are Javascript arrays primitives? Strings? Objects?
Arrays are objects.
However, unlike regular objects, arrays have certain special features.
Arrays have an additional object in their prototype chain - namely
Array.prototype
. This object contains so-called Array methods which can be called on array instances. (List of methods is here: http://es5.github.com/#x15.4.4)Arrays have a
length
property (which is live, ergo, it auto-updates) (Read here: http://es5.github.com/#x15.4.5.2)Arrays have a special algorithm regarding defining new properties (Read here: http://es5.github.com/#x15.4.5.1). If you set a new property to an array and that property's name is a sting which can be coerced to an integer number (like
'1'
,'2'
,'3'
, etc.) then the special algorithm applies (it is defined on p. 123 in the spec)
Other than these 3 things, arrays are just like regular objects.
Read about arrays in the spec: http://es5.github.com/#x15.4
Passing Arrays to a method inconsistent with passing primitive data type to a method
However, my question is, why such a design was chosen for Arrays.
There are several main reasons.
The first is performance - it would lead to extremely poor performance if a new copy of the array had to be created every single time a method was called on it, especially for recursive calls.
Had the same been done for arrays, it would've allowed us to have a
different copy of the array for each frame of the recursive function,
which would've been very handy.
The second is that you already have the option of passing a copy of the array if you want to - you can create a copy manually and pass that. This way the programmer has the most control - they can choose to let method calls modify the array, or they can choose to pass a copy, allowing each method call its on version of the array to work with. If we forced the programmer to use a copy all the time, they would lose the option of letting method calls modify the array, which can be extremely useful in some situations. The current design gives the programmer the most options.
Why couldn't it be that, just like for a primitive data type...
The last reason is that an array is not a primitive data type - it is an object. The decision was most likely made to make arrays as consistent as possible with the way other objects in Java behave.
java : Understanding Arrays.asList(T...array) method for primitive types
There are obviously 3 questions here so lets tackle them one by one:
- How exactly do I expect that list methods will work when I'm expecting an List of Integer and getting a List of int[] ?
Well, List
methods will work exactly as expected, a List<T>
is a list of types T
. Here T
is an int[]
so a List<int[]>
will contains arrays as each element:
[{1, 2}, {3, 4}, {1, 6}]
So get(i)
will return the ith
element. In the case of Arrays.asList
the List
contains a single element, namely the int[]
so:
int[] array = {210,211,212};
List<int[]> list = Arrays.asList(array);
Will be
[{210, 211, 212}]
And so
list.get(0)[0] == 210
In case of Strings the return type is List of String and not List of String[]. What sort of implementation differences are there?
String
is an Object
, not a primitive type. The difference follows from that.
- What good is this method for primitives if things are so uncertain?
Things are not uncertain. This method results in defined and predictable behaviour. It's just not very useful for primitives. This is (yet another) side effect of combining Java's type system with generics.
Note with Java 8 the conversion of an int[]
to a List<Integer>
is very simple:
List<Integer> list = Arrays.stream(array).
boxed().
collect(toList());
Cast primitive type array into object array in java
Primitive type cannot be transformed in this way.
In your case, there is an array of double values, cause of 3.14.
This will work:
List<Object> objectList = new ArrayList<Object>();
objectList.addAll(Arrays.asList(0,1,2,3.14,4));
Even this works :
List<Object> objectList = new ArrayList<Object>();
objectList.addAll(Arrays.asList(0,"sfsd",2,3.14,new Regexp("Test")));
for(Object object:objectList)
{
System.out.println(object);
}
UPDATE
Ok, there as there was said, there is not direct way to cast a primitive array to an Object[].
If you want a method that transforms any array in String, I can suggest this way
public class CastArray {
public static void main(String[] args) {
CastArray test = new CastArray();
test.TestObj(new int[]{1, 2, 4});
test.TestObj(new char[]{'c', 'a', 'a'});
test.TestObj(new String[]{"fdsa", "fdafds"});
}
public void TestObj(Object obj) {
if (!(obj instanceof Object[])) {
if (obj instanceof int[]) {
for (int i : (int[]) obj) {
System.out.print(i + " ");
}
System.out.println("");
}
if (obj instanceof char[]) {
for (char c : (char[]) obj) {
System.out.print(c + " ");
}
System.out.println("");
}
//and so on, for every primitive type.
} else {
System.out.println(Arrays.asList((Object[]) obj));
}
}
}
Yes, it's annoying to write a loop for every primitive type, but there is no other way, IMHO.
Related Topics
How to Define a List Bean in Spring
Lambda Expression and Generic Defined Only in Method
Why to Use Swingutilities.Invokelater in Main Method
Read Properties File Outside Jar File
Why Do I Get Java.Lang.Abstractmethoderror When Trying to Load a Blob in the Db
How Do Synchronized Static Methods Work in Java and How to Use It for Loading Hibernate Entities
Sorting Using Comparator- Descending Order (User Defined Classes)
Differencebetween Jvm, Jdk, Jre & Openjdk
Socket Programming Multiple Client to One Server
Ignore Fields from Java Object Dynamically While Sending as JSON from Spring MVC
How to Find Nth Occurrence of Character in a String
Allowing Java to Use an Untrusted Certificate for Ssl/Https Connection
How to Remove the Last Character from a String
Override Java System.Currenttimemillis for Testing Time Sensitive Code