Why arrays can be used in the generic in JAVA? [duplicate] - java

This question already has answers here:
Primitive arrays as a generic parameter [duplicate]
(4 answers)
Closed 1 year ago.
int is primitive type in java. Why is int[] usable as a generic type?
I can write code like this and compile it.
List<int[]> test = new ArrayList<>();

Indeed int is a primitive however an array of integers, int[], isn't.
Java Docs define an array as,
An array is a container object that holds a fixed number of values of
a single type.
As you can see an array is an object with class hierarchy as following,
java.lang.Object
java.util.Arrays
So arrays in java are basically objects of type java.util.Arrays. The same class also provides all the good operations you can perform on Arrays.
Back to your question, you're right, Java doesn't allow passing primitives as type parameter when you're using generics.
You cannot do this,
List<int> test = new ArrayList<int>();
However you can do generics with Integer class just fine,
List<Integer> test = new ArrayList<Integer>();
The reasons for not allowing primitives are discussed here on stackoverflow.
One might think, Java does support autoboxing so why not simply autobox primitives to their equivalent classes. Well that is a design choice. Primitives are efficient and cost less memory. Designers probably rightly decided to not assume autoboxing would serve equivalent efficiency.

Related

Varargs methods and primitive types [duplicate]

This question already has answers here:
Arrays.asList() not working as it should?
(12 answers)
Closed 4 years ago.
In Effective Java J. Bloch mentioned that it was not safe to use varargs method with primitive types. Percisely, Arrays.asList(1, 2, 4) had return type List<int[]> and it sounds quite reasonble. Now I tried to reproduce this behaviour myself and couldn't:
My question is why is the type deduced to List<Integer> but not to List<int[]> as he stated? Does it mean, that in Java 8 the problem about varargs is not relevant anymore and we can safely use them anywhere we want if we don't care about performance too much.
Author most probably meant that you can't pass array of primitive type elements and expect it to be boxed like
int[] intArray = {1,2,3};
Arrays.asList(intArray);
which will return List<int[]> not List<Integer> since there is no autoboxing of arrays like int[]->Integer[] so only possible type which can be used by T... vararg is int[] since generic type T can't represent primitive type.
Other possible problem is that you are reading first edition of book (released in 2001) but autoboxing was added in Java 1.5 (Java 5.0) which was released in 2004.

How to back a generic data structure with an array in Java? [duplicate]

This question already has answers here:
How to create a generic array in Java?
(32 answers)
Closed 8 years ago.
I have a good understanding of data structures and can happily implement them in C++ without issue; I get a little tripped up in Java though due to the generic implementation constraints.
Specifically, I get confused when I'm trying to create a data structure backed by an array. I know, for example, that I cannot do this:
public class HashTable<T> {
private T[] table;
public HashTable() {
table = new T[10]; //Type param T cannot be instantiated directly.
}
}
I also know that if I back my generic array list with an object array, I'm going to have to suppress a number of "unchecked cast" warnings which seems of ill form.
What is the best way to create an array-based data structure in Java? Is there some trick that can be used to do it in a cleaner manner than just creating a straight object array and dealing with the messy casting?
Instead of using a raw array, use an ArrayList<T>. It's basically a generic wrapper around an array, with a bunch of additional features.

Is there a class to an array in java [duplicate]

This question already has answers here:
Is an array an object in Java?
(14 answers)
Closed 9 years ago.
We know that Arrays are objects in Java. I believe to create an object in Object oriented languages(if not we can have it in a separate discussion), we need a blueprint of it(a class). But I'm not sure or cannot find the class for which the object is being created for arrays when the new operator is used. If there is a class for arrays in java, then how will the hierarchy look like?
If there is no class, then how are the objects instantiated? And what is the reason behind having an object type without a class?
Arrays are created by virtual machine with a special instruction called newarray, so think them as a special construct.
From JVM Spec:
3.9. Arrays
Java Virtual Machine arrays are also objects. Arrays are created and manipulated using a distinct set of instructions. The newarray instruction is used to create an array of a numeric type. The code:
Also read more from JLS for class hierarchy of an array.
The direct superclass of an array type is Object.
An array, let's say an Object[], is a special kind of variable, just as primitives are. Its type is Object[], not Object. Java is not a "fully" object oriented language, such as Ruby is; it has some special data types like arrays and primitives.
The logic is reverse to your.
An object is a class instance or an array.
But as Java is OOP language, everything must be represented as object. When you reflect your code you can use class java.lang.reflect.Array that represent Array.
arrays are not primitive in java. An array is a container object that holds a fixed number of values of a single type.
System.out.print(int[].class.toString());
It successfully prints and proves it has a concrete class in background and same applied for all other array types.
Find documentaion in detail.
Yes, Java has classes for arrays, see http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.8 Class Objects for Arrays, e.g.
Class<int[]> cls = int[].class;
These classes are dynamically created by JVM.
There is no hierarchy among arrays of primitive types
int[] a = new long[1];
Produces compile time error. The hiearchy of Object array types is the same as with Object types
Object[] a = new String[1];

Do collections convert int to integers sometimes?

I was reading somewhere that even if I use int primitives, adding them to certain types of collections may result in a conversion from int to integers.
When is this the case?
Java collections can only contain objects. Therefore, all collections will Autobox any primitive types you pass them into their equivalent object (boxed) form before storing them. So int primitives will be converted to Integers before being stored in a collection.
Java generics and require their type to be a full-fledged object, which primitives obviously aren't. Note that collections before generics were introduced worked with Objects, so they also required full-fledged objects. Java also introduced auto-boxing and auto-unboxing to make this requirement less of a pain, that means that when you pass an int where a method expects an Integer, an appropriate Integer will automatically be created with the correct value.
It is called auto-boxing and all collections does this since Java 5. It is from int primitive to java.lang.Integer wrapper class (not integers as you mentioned in your post).
The Java guide on autoboxing says about this:
... you can’t put an int (or other primitive value) into a collection. Collections can only hold object references, so you have to box
primitive values into the appropriate wrapper class
Since the JDK's collections maintain data as java.lang.Object references (or Object arrays) internally, they all do have to store the values in boxed/wrapped form.
If you do want to reduce the memory footprint for specialized collections, consider using Trove, which has specialized implementations that store data in primitive arrays.

Why primitive datatypes are not allowed in java.util.ArrayList? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Storing primitive values in a Java collection?
ArrayList accepts only reference types as its element, not primitive datatypes.
When trying to do so it produces a compile time error.
What is the concept behind this? It seems like a limitation, is it not?
All collection classes of java store memory location of the objects they collect. The primitive values do not fit in to the same definition.
To circumvent this problem, JDK5 and onwards have autoboxing - wherein the primitives are converted to appropriate objects and back when they are added or read from the collections. Refer to the official JDK tutorial on this topic.
Checking the JDK5 source code for ArrayList helps better understanding: creating an ArrayList<E> includes casting an Object[] array to E[].
Because Java can only use class (and not primitive types) and arrays (also arrays for primitives) for generics (between < and >).
List list; That is also a reason why there are wrapper classes for primitive types:
int -> Integer
boolean -> Boolean
double -> Double
byte -> Byte etc...

Categories

Resources