ArrayList type mismatch - java

I made a little program to illustrate my question. If I strip the casting to BigInteger in the line of the return (12th line), I get a compiling error of "Incompatible types". But if I do the casting, the line before (11th) prints out that the type of the returned value is BigInteger. If it's a BigInteger, why do I have to cast?
public class ProbArrBig {
public static void main (String args[]) {
}
private static BigInteger myFunction() {
ArrayList myArr = new ArrayList();
BigInteger myNumber = BigInteger.valueOf(23452439);
myArr.add(myNumber);
System.out.println("Type of myArr.get(0): "+myArr.get(0).getClass().getName());
return (BigInteger) myArr.get(0); //Doesn't work without (BigInteger)
}
}

It should be using
ArrayList<BigInteger> myArr = new ArrayList<BigInteger>()
This is called generics and indicate that the list contains BigInteger
objects, therefore when a value it is retrieved from the list you are indicating that it will be of that specific type.

The ArrayList class is designed to take a generics type <E> as follows:
ArrayList<Integer> myArr = new ArrayList<Integer>();
Since you did not provide the actual type for <E> for your particular instance, what you actually have is
ArrayList<Object> myArr = newArrayList<Object>();
Therefore, your return of myArr does not match your method signature unless you cast BigInteger, which you are able to do because everything inherits from the Object class. If you change your method to return a type Object, you will see that the code will compile without error, without the cast.

Related

What is the proper way to convert the generic type array and use it in java? [duplicate]

Due to the implementation of Java generics, you can't have code like this:
public class GenSet<E> {
private E a[];
public GenSet() {
a = new E[INITIAL_ARRAY_LENGTH]; // error: generic array creation
}
}
How can I implement this while maintaining type safety?
I saw a solution on the Java forums that goes like this:
import java.lang.reflect.Array;
class Stack<T> {
public Stack(Class<T> clazz, int capacity) {
array = (T[])Array.newInstance(clazz, capacity);
}
private final T[] array;
}
But I really don't get what's going on.
I have to ask a question in return: is your GenSet "checked" or "unchecked"?
What does that mean?
Checked: strong typing. GenSet knows explicitly what type of objects it contains (i.e. its constructor was explicitly called with a Class<E> argument, and methods will throw an exception when they are passed arguments that are not of type E. See Collections.checkedCollection.
-> in that case, you should write:
public class GenSet<E> {
private E[] a;
public GenSet(Class<E> c, int s) {
// Use Array native method to create array
// of a type only known at run time
#SuppressWarnings("unchecked")
final E[] a = (E[]) Array.newInstance(c, s);
this.a = a;
}
E get(int i) {
return a[i];
}
}
Unchecked: weak typing. No type checking is actually done on any of the objects passed as argument.
-> in that case, you should write
public class GenSet<E> {
private Object[] a;
public GenSet(int s) {
a = new Object[s];
}
E get(int i) {
#SuppressWarnings("unchecked")
final E e = (E) a[i];
return e;
}
}
Note that the component type of the array should be the erasure of the type parameter:
public class GenSet<E extends Foo> { // E has an upper bound of Foo
private Foo[] a; // E erases to Foo, so use Foo[]
public GenSet(int s) {
a = new Foo[s];
}
...
}
All of this results from a known, and deliberate, weakness of generics in Java: it was implemented using erasure, so "generic" classes don't know what type argument they were created with at run time, and therefore can not provide type-safety unless some explicit mechanism (type-checking) is implemented.
You can do this:
E[] arr = (E[])new Object[INITIAL_ARRAY_LENGTH];
This is one of the suggested ways of implementing a generic collection in Effective Java; Item 26. No type errors, no need to cast the array repeatedly. However this triggers a warning because it is potentially dangerous, and should be used with caution. As detailed in the comments, this Object[] is now masquerading as our E[] type, and can cause unexpected errors or ClassCastExceptions if used unsafely.
As a rule of thumb, this behavior is safe as long as the cast array is used internally (e.g. to back a data structure), and not returned or exposed to client code. Should you need to return an array of a generic type to other code, the reflection Array class you mention is the right way to go.
Worth mentioning that wherever possible, you'll have a much happier time working with Lists rather than arrays if you're using generics. Certainly sometimes you don't have a choice, but using the collections framework is far more robust.
Here's how to use generics to get an array of precisely the type you’re looking for while preserving type safety (as opposed to the other answers, which will either give you back an Object array or result in warnings at compile time):
import java.lang.reflect.Array;
public class GenSet<E> {
private E[] a;
public GenSet(Class<E[]> clazz, int length) {
a = clazz.cast(Array.newInstance(clazz.getComponentType(), length));
}
public static void main(String[] args) {
GenSet<String> foo = new GenSet<String>(String[].class, 1);
String[] bar = foo.a;
foo.a[0] = "xyzzy";
String baz = foo.a[0];
}
}
That compiles without warnings, and as you can see in main, for whatever type you declare an instance of GenSet as, you can assign a to an array of that type, and you can assign an element from a to a variable of that type, meaning that the array and the values in the array are of the correct type.
It works by using class literals as runtime type tokens, as discussed in the Java Tutorials. Class literals are treated by the compiler as instances of java.lang.Class. To use one, simply follow the name of a class with .class. So, String.class acts as a Class object representing the class String. This also works for interfaces, enums, any-dimensional arrays (e.g. String[].class), primitives (e.g. int.class), and the keyword void (i.e. void.class).
Class itself is generic (declared as Class<T>, where T stands for the type that the Class object is representing), meaning that the type of String.class is Class<String>.
So, whenever you call the constructor for GenSet, you pass in a class literal for the first argument representing an array of the GenSet instance's declared type (e.g. String[].class for GenSet<String>). Note that you won't be able to get an array of primitives, since primitives can't be used for type variables.
Inside the constructor, calling the method cast returns the passed Object argument cast to the class represented by the Class object on which the method was called. Calling the static method newInstance in java.lang.reflect.Array returns as an Object an array of the type represented by the Class object passed as the first argument and of the length specified by the int passed as the second argument. Calling the method getComponentType returns a Class object representing the component type of the array represented by the Class object on which the method was called (e.g. String.class for String[].class, null if the Class object doesn't represent an array).
That last sentence isn't entirely accurate. Calling String[].class.getComponentType() returns a Class object representing the class String, but its type is Class<?>, not Class<String>, which is why you can't do something like the following.
String foo = String[].class.getComponentType().cast("bar"); // won't compile
Same goes for every method in Class that returns a Class object.
Regarding Joachim Sauer's comment on this answer (I don't have enough reputation to comment on it myself), the example using the cast to T[] will result in a warning because the compiler can't guarantee type safety in that case.
Edit regarding Ingo's comments:
public static <T> T[] newArray(Class<T[]> type, int size) {
return type.cast(Array.newInstance(type.getComponentType(), size));
}
This is the only answer that is type safe
E[] a;
a = newArray(size);
#SafeVarargs
static <E> E[] newArray(int length, E... array)
{
return Arrays.copyOf(array, length);
}
To extend to more dimensions, just add []'s and dimension parameters to newInstance() (T is a type parameter, cls is a Class<T>, d1 through d5 are integers):
T[] array = (T[])Array.newInstance(cls, d1);
T[][] array = (T[][])Array.newInstance(cls, d1, d2);
T[][][] array = (T[][][])Array.newInstance(cls, d1, d2, d3);
T[][][][] array = (T[][][][])Array.newInstance(cls, d1, d2, d3, d4);
T[][][][][] array = (T[][][][][])Array.newInstance(cls, d1, d2, d3, d4, d5);
See Array.newInstance() for details.
In Java 8, we can do a kind of generic array creation using a lambda or method reference. This is similar to the reflective approach (which passes a Class), but here we aren't using reflection.
#FunctionalInterface
interface ArraySupplier<E> {
E[] get(int length);
}
class GenericSet<E> {
private final ArraySupplier<E> supplier;
private E[] array;
GenericSet(ArraySupplier<E> supplier) {
this.supplier = supplier;
this.array = supplier.get(10);
}
public static void main(String[] args) {
GenericSet<String> ofString =
new GenericSet<>(String[]::new);
GenericSet<Double> ofDouble =
new GenericSet<>(Double[]::new);
}
}
For example, this is used by <A> A[] Stream.toArray(IntFunction<A[]>).
This could also be done pre-Java 8 using anonymous classes but it's more cumbersome.
You do not need to pass the Class argument to the constructor.
Try this.
public class GenSet<T> {
private final T[] array;
#SafeVarargs
public GenSet(int capacity, T... dummy) {
if (dummy.length > 0)
throw new IllegalArgumentException(
"Do not provide values for dummy argument.");
this.array = Arrays.copyOf(dummy, capacity);
}
#Override
public String toString() {
return "GenSet of " + array.getClass().getComponentType().getName()
+ "[" + array.length + "]";
}
}
and
GenSet<Integer> intSet = new GenSet<>(3);
System.out.println(intSet);
System.out.println(new GenSet<String>(2));
result:
GenSet of java.lang.Integer[3]
GenSet of java.lang.String[2]
This is covered in Chapter 5 (Generics) of Effective Java, 2nd Edition, item 25...Prefer lists to arrays
Your code will work, although it will generate an unchecked warning (which you could suppress with the following annotation:
#SuppressWarnings({"unchecked"})
However, it would probably be better to use a List instead of an Array.
There's an interesting discussion of this bug/feature on the OpenJDK project site.
Java generics work by checking types at compile time and inserting appropriate casts, but erasing the types in the compiled files. This makes generic libraries usable by code which doesn't understand generics (which was a deliberate design decision) but which means you can't normally find out what the type is at run time.
The public Stack(Class<T> clazz,int capacity) constructor requires you to pass a Class object at run time, which means class information is available at runtime to code that needs it. And the Class<T> form means that the compiler will check that the Class object you pass is precisely the Class object for type T. Not a subclass of T, not a superclass of T, but precisely T.
This then means that you can create an array object of the appropriate type in your constructor, which means that the type of the objects you store in your collection will have their types checked at the point they are added to the collection.
Although the thread is dead, I would like to draw your attention to this.
Generics are used for type checking during compile time. Therefore, the purpose is to check
What comes in is what you need.
What you return is what the consumer needs.
Check this:
Don't worry about typecasting warnings when you are writing a generic class; worry when you are using it.
What about this solution?
#SafeVarargs
public static <T> T[] toGenericArray(T ... elems) {
return elems;
}
It works and looks too simple to be true. Is there any drawback?
The example is using Java reflection to create an array. Doing this is generally not recommended, since it isn't typesafe. Instead, what you should do is just use an internal List, and avoid the array at all.
Look also to this code:
public static <T> T[] toArray(final List<T> obj) {
if (obj == null || obj.isEmpty()) {
return null;
}
final T t = obj.get(0);
final T[] res = (T[]) Array.newInstance(t.getClass(), obj.size());
for (int i = 0; i < obj.size(); i++) {
res[i] = obj.get(i);
}
return res;
}
It converts a list of any kind of object to an array of the same type.
I have found a quick and easy way that works for me. Note that i have only used this on Java JDK 8. I don't know if it will work with previous versions.
Although we cannot instantiate a generic array of a specific type parameter, we can pass an already created array to a generic class constructor.
class GenArray <T> {
private T theArray[]; // reference array
// ...
GenArray(T[] arr) {
theArray = arr;
}
// Do whatever with the array...
}
Now in main we can create the array like so:
class GenArrayDemo {
public static void main(String[] args) {
int size = 10; // array size
// Here we can instantiate the array of the type we want, say Character (no primitive types allowed in generics)
Character[] ar = new Character[size];
GenArray<Character> = new Character<>(ar); // create the generic Array
// ...
}
}
For more flexibility with your arrays you can use a linked list eg. the ArrayList and other methods found in the Java.util.ArrayList class.
Passing a list of values...
public <T> T[] array(T... values) {
return values;
}
I made this code snippet to reflectively instantiate a class which is passed for a simple automated test utility.
Object attributeValue = null;
try {
if(clazz.isArray()){
Class<?> arrayType = clazz.getComponentType();
attributeValue = Array.newInstance(arrayType, 0);
}
else if(!clazz.isInterface()){
attributeValue = BeanUtils.instantiateClass(clazz);
}
} catch (Exception e) {
logger.debug("Cannot instanciate \"{}\"", new Object[]{clazz});
}
Note this segment:
if(clazz.isArray()){
Class<?> arrayType = clazz.getComponentType();
attributeValue = Array.newInstance(arrayType, 0);
}
for array initiating where Array.newInstance(class of array, size of array). Class can be both primitive (int.class) and object (Integer.class).
BeanUtils is part of Spring.
The forced cast suggested by other people did not work for me, throwing an exception of illegal casting.
However, this implicit cast worked fine:
Item<K>[] array = new Item[SIZE];
where Item is a class I defined containing the member:
private K value;
This way you get an array of type K (if the item only has the value) or any generic type you want defined in the class Item.
Actually an easier way to do so, is to create an array of objects and cast it to your desired type like the following example:
T[] array = (T[])new Object[SIZE];
where SIZE is a constant and T is a type identifier
No one else has answered the question of what is going on in the example you posted.
import java.lang.reflect.Array;
class Stack<T> {
public Stack(Class<T> clazz, int capacity) {
array = (T[])Array.newInstance(clazz, capacity);
}
private final T[] array;
}
As others have said generics are "erased" during compilation. So at runtime an instance of a generic doesn't know what its component type is. The reason for this is historical, Sun wanted to add generics without breaking the existing interface (both source and binary).
Arrays on the other hand do know their component type at runtime.
This example works around the problem by having the code that calls the constructor (which does know the type) pass a parameter telling the class the required type.
So the application would construct the class with something like
Stack<foo> = new Stack<foo>(foo.class,50)
and the constructor now knows (at runtime) what the component type is and can use that information to construct the array through the reflection API.
Array.newInstance(clazz, capacity);
Finally we have a type cast because the compiler has no way of knowing that the array returned by Array#newInstance() is the correct type (even though we know).
This style is a bit ugly but it can sometimes be the least bad solution to creating generic types that do need to know their component type at runtime for whatever reason (creating arrays, or creating instances of their component type, etc.).
I found a sort of a work around to this problem.
The line below throws generic array creation error
List<Person>[] personLists=new ArrayList<Person>()[10];
However if I encapsulate List<Person> in a separate class, it works.
import java.util.ArrayList;
import java.util.List;
public class PersonList {
List<Person> people;
public PersonList()
{
people=new ArrayList<Person>();
}
}
You can expose people in the class PersonList thru a getter. The line below will give you an array, that has a List<Person> in every element. In other words array of List<Person>.
PersonList[] personLists=new PersonList[10];
I needed something like this in some code I was working on and this is what I did to get it to work. So far no problems.
Generic array creation is disallowed in java but you can do it like
class Stack<T> {
private final T[] array;
public Stack(int capacity) {
array = (T[]) new Object[capacity];
}
}
According to vnportnoy the syntax
GenSet<Integer> intSet[] = new GenSet[3];
creates an array of null references, to be filled as
for (int i = 0; i < 3; i++)
{
intSet[i] = new GenSet<Integer>();
}
which is type safe.
You could create an Object array and cast it to E everywhere. Yeah, it's not very clean way to do it but it should at least work.
try this.
private int m = 0;
private int n = 0;
private Element<T>[][] elements = null;
public MatrixData(int m, int n)
{
this.m = m;
this.n = n;
this.elements = new Element[m][n];
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
this.elements[i][j] = new Element<T>();
}
}
}
An easy, albeit messy workaround to this would be to nest a second "holder" class inside of your main class, and use it to hold your data.
public class Whatever<Thing>{
private class Holder<OtherThing>{
OtherThing thing;
}
public Holder<Thing>[] arrayOfHolders = new Holder<Thing>[10]
}
Maybe unrelated to this question but while I was getting the "generic array creation" error for using
Tuple<Long,String>[] tupleArray = new Tuple<Long,String>[10];
I find out the following works (and worked for me) with #SuppressWarnings({"unchecked"}):
Tuple<Long, String>[] tupleArray = new Tuple[10];
I'm wondering if this code would create an effective generic array?
public T [] createArray(int desiredSize){
ArrayList<T> builder = new ArrayList<T>();
for(int x=0;x<desiredSize;x++){
builder.add(null);
}
return builder.toArray(zeroArray());
}
//zeroArray should, in theory, create a zero-sized array of T
//when it is not given any parameters.
private T [] zeroArray(T... i){
return i;
}
Edit: Perhaps an alternate way of creating such an array, if the size you required was known and small, would be to simply feed the required number of "null"s into the zeroArray command?
Though obviously this isn't as versatile as using the createArray code.
You could use a cast:
public class GenSet<Item> {
private Item[] a;
public GenSet(int s) {
a = (Item[]) new Object[s];
}
}
I actually found a pretty unique solution to bypass the inability to initiate a generic array. What you have to do is create a class that takes in the generic variable T like so:
class GenericInvoker <T> {
T variable;
public GenericInvoker(T variable){
this.variable = variable;
}
}
and then in your array class just have it start like so:
GenericInvoker<T>[] array;
public MyArray(){
array = new GenericInvoker[];
}
starting a new Generic Invoker[] will cause an issue with unchecked but there shouldn't actually be any issues.
To get from the array you should call the array[i].variable like so:
public T get(int index){
return array[index].variable;
}
The rest, such as resizing the array can be done with Arrays.copyOf() like so:
public void resize(int newSize){
array = Arrays.copyOf(array, newSize);
}
And the add function can be added like so:
public boolean add(T element){
// the variable size below is equal to how many times the add function has been called
// and is used to keep track of where to put the next variable in the array
arrays[size] = new GenericInvoker(element);
size++;
}
If you really want to wrap a generic array of fixed size you will have a method to add data to that array, hence you can initialize properly the array there doing something like this:
import java.lang.reflect.Array;
class Stack<T> {
private T[] array = null;
private final int capacity = 10; // fixed or pass it in the constructor
private int pos = 0;
public void push(T value) {
if (value == null)
throw new IllegalArgumentException("Stack does not accept nulls");
if (array == null)
array = (T[]) Array.newInstance(value.getClass(), capacity);
// put logic: e.g.
if(pos == capacity)
throw new IllegalStateException("push on full stack");
array[pos++] = value;
}
public T pop() throws IllegalStateException {
if (pos == 0)
throw new IllegalStateException("pop on empty stack");
return array[--pos];
}
}
in this case you use a java.lang.reflect.Array.newInstance to create the array, and it will not be an Object[], but a real T[].
You should not worry of it not being final, since it is managed inside your class.
Note that you need a non null object on the push() to be able to get the type to use, so I added a check on the data you push and throw an exception there.
Still this is somewhat pointless: you store data via push and it is the signature of the method that guarantees only T elements will enter. So it is more or less irrelevant that the array is Object[] or T[].

How and when are variables casted to types declared in generic type parameters?

public static void main(String[] args) {
List<Integer> integers = new ArrayList<>();
integers.add(5); //element #0
List list = integers;
list.add("foo"); //element #1
integers.get(1); //no error
System.out.println(integers.get(1)); //no error, prints "foo"
Integer i = integers.get(1); //throws ClassCastException
}
I'm trying to understand the process of casting variables of type, declared as a generic type parameter, and I'm a bit confused.
So, you may see in the example I've provided, that after we create a non-parametrized List, which refers to the same object that List<Integer>, then we can add any objects to that list (OK, nothing surprising here) and, what confuses me so much, we can extract non-Integer values from List<Integer> integers. Why isn't ClassCastException thrown at the first or the second call of integers.get(1)?
I assumed that methods returning parameter types, in fact always return Object and those returned values are implicitly tried to be converted to
l-value type or method parameter type at runtime (as there are no generics at runtime), however the following test convinced me that Integer is always preferred over Object:
public static void main(String[] args) {
List<Integer> integers = new ArrayList<>();
integers.add(5); //element #0
List list = integers;
list.add("foo"); //element #1
print(integers.get(1));
}
private static void print(Object var) {
System.out.println(var);
}
//this method is entered
private static void print(Integer var) {
System.out.println(var);
}
private static void print(String var) {
System.out.println(var);
}
Another interesting fact is that although elements of ArrayList are stored in Object[] array, they are always converted to a type defined in type parameter before being returned in method get():
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
E elementData(int index) {
return (E) elementData[index];
}
So, if anyone may point me to the documentation where these questions are explained step by step, I would be very thankful
The compiler inserts casts when casts are needed. The method System.out.println has a parameter of type Object, so no cast to Integer is required.
In the case of your three print methods, the method with a parameter of type Integer is chosen, so the compiler inserts a cast. The choice of which of the three methods to use occurs at compile time based on a complicated set of rules. These rules use the generic information to see that integers.get(1) has type Integer, and so the Integer version is chosen and the cast is needed. As a result, the code is more or less equivalent to Java 4 code
List integers = new ArrayList();
integers.add("foo");
integers.add(Integer.valueOf(5)); // No autoboxing in Java 4!
print((Integer) integers.get(1)); // Cast inserted by compiler
The cast to (E) in the final part of your question does not actually do anything at runtime, and so will not throw a ClassCastException. It is only needed to make the code compile. You are telling the compiler that, yes, you are sure the Object is really an E and won't cause an exception later on (although you have subverted that by mixing raw and generic types).

Is-a relationship with parameterized references

This has probably been asked before but i haven't been able to find a question.
I would like to understand the underlying reasons why does the following block of code not compile:
public class Box<T> {
private T value;
public Box(T value) {
this.value = value;
}
public T getValue() {
return value;
}
public static void main(String[] args) {
Box<Integer> i = new Box<Integer>(13);
// does not compile
Box<Object> o = i;
}
}
One way to look at it is, let's assume Box defined a void setValue(T val) method.
Box<Object> o = i;
o.setValue("a string");
Integer x = i.getValue(); // ?!
The problem is mentioned in java documentation here (it is similar to Vlad's answer):
https://docs.oracle.com/javase/tutorial/extra/generics/subtype.html
Let's test your understanding of generics. Is the following code snippet legal?
List<String> ls = new ArrayList<String>(); // 1
List<Object> lo = ls; // 2
Line 1 is certainly legal. The trickier part of the question is line 2. This boils down to the question: is a List of String a List of Object. Most people instinctively answer, "Sure!"
Well, take a look at the next few lines:
lo.add(new Object()); // 3
String s = ls.get(0); // 4: Attempts to assign an Object to a String!
Here we've aliased ls and lo. Accessing ls, a list of String, through the alias lo, we can insert arbitrary objects into it. As a result ls does not hold just Strings anymore, and when we try and get something out of it, we get a rude surprise.
Firstly you cannot cast parameterized types. Check this oracle doc.
Typically, you cannot cast to a parameterized type unless it is
parameterized by unbounded wildcards. For example:
List li = new ArrayList<>();
List ln = (List) li; // compile-time error
Hence the line Box<Object> o = i; causes compile time error.
Even though while creating Box object you have not specified the generic parameter, but using constructor parameter type java Type inference the constructing object's type.
You can assign any reference to an Object reference but when generics kicks in, the exact generic type is matched at compile time. Hence it's not working. If you change to Box<? extends Object> o = i; it'll work since the generic type matches the contained type.

How to create generic array? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java how to: Generic Array creation
How to create an array of type T[] in Java? I can't use Arrays.newInstance() since I have no objects of Class<T>. Is there a generic version of newInstance somewhere?
My method prototype follows:
public <T> T[][] distribute(T ... balls) {
T[][] answer = ????
// filling answer with data
return answer;
}
UPDATE
Sorry in example above I can take class from balls. But suppose I have no such a variable.
public <T> T[][] distribute() {
T[][] answer = ????
// filling answer with data
return answer;
}
or
class<T> {
public T[][] distribute() {
T[][] answer = ????
// filling answer with data
return answer;
}
}
UPDATE2
This example also does not work:
public abstract class GenericArray<T> {
abstract public T create();
public T[] gen1() {
T[] ans = (T[]) new Object[3];
ans[0] = create();
ans[1] = create();
ans[2] = create();
return ans;
}
public Integer[] gen2() {
Integer[] ans = new Integer[3];
ans[0] = new Integer(0);
ans[1] = new Integer(0);
ans[2] = new Integer(0);
return ans;
}
public static void main(String[] args) {
GenericArray<Integer> a = new GenericArray<Integer>() {
#Override
public Integer create() {
return new Integer(0);
}
};
Integer[] b = a.gen2();
Integer[] c = a.gen1(); // this causes ClassCastException
System.out.println("done");
}
}
1. Arrays are Not Generic
2. Thats the reason Arrays are checked during compile as well as runtime, where as Collections can be Generic and its checked only during the compile time....
(T[][]) new Object[size][size]
What you ask is not possible. An array knows its component type at runtime, and arrays of different component types are different runtime types. That's why when you create the array, you need to know the component type at runtime.
Since your method is generic over T, the caller can dictate the T it wants to use to the compiler every time it calls this method. So consider how absurd this is:
String[][] foo = this.<String>distribute();
Integer[][] bar = this.<Integer>distribute();
The compiled code on the right side of this is identical for the two lines. The .<String> stuff is just hints to the compiler, and do not affect the compiled code. So this means that distribute() must return something that is both String[][] and Integer[][] (which is then checked at runtime, since String[][] and Integer[][] are reified runtime types). The only value that can satisfy this is null.
(You might ask, why does this problem not occur for methods that return List<T>? The answer is that, unlike for arrays, there is only one class List at runtime. And lists do not know their component types at runtime. So a new ArrayList<Foo>() and a new ArrayList<Bar>() are exactly the same at runtime. So they don't have this problem.)
Another analogy of what is happening here: So array types have an inheritance pattern that follows the inheritance of their component types. So Integer[][] is a subclass of Object[][]. And in fact, all T[][] are subclasses of Object[][]. So instead of Object[][] and its subclasses, let's consider a non-array class, MyBaseClass, which has a bunch of subclasses. Then, what you are basically asking is to be able to generically create an instance of an unknown subclass of MyBaseClass (determined by a type parameter).
<T extends MyBaseClass> T distribute() {
T answer = //...?
return answer;
}
I hope you can see why this is impossible.
Do: T[][] answer = (T[][]) new Object[][];
T will be erased anyway by compiler to Object. Of course you need to know the size of the array.
Update:
In your new example you get the exception here:
Integer[] c = a.gen1(); // this causes ClassCastException
Because you are trying to cast an Object[] to an Integer[]. Not possible.
What you get back is an Object[] but containing Integer references. So you would need to do:
Object[] c = a.gen1();
for(Object n:c){
Integer nn = (Integer) n;
}
This is ok since n is an Integer.
But as a general rule: If you need to collect parameterized type objects, simply use an ArrayList. In your example where you don't even have the actual class to instantiate the array via reflection it is the only sensible choice

Yet another java generics confusion

Let us have the following code:
public class TestGenerics {
static <T> void mix(ArrayList<T> list, T t) {
System.out.println(t.getClass().getName());
T item = list.get(0);
t = item;
System.out.println(t.getClass().getName());
}
public static void main(String[] args) {
ArrayList<Object> list = new ArrayList<Object>();
list.add(new Integer(3));
mix(list, "hello world");
}
}
In the output I get:
java.lang.String
java.lang.Integer
It's nonsense - we've just assigned Integer to String without getting ClassCastException! We can't write it like that:
String s = new Integer(3);
but this is what we have just done here.
Is it a bug or something?
In your case as list is an ArrayList<Object>, T is considered as an Object so you can see things as :
static void mix(ArrayList<Object> list, Object t)
So you assigned an Integer to an Object (which was a String before).
Object obj = new Integer(3);
obj = "Hello"; //No CCE here
You have a list of Object. One of the objects in the list is a String, the other is an Integer. getClass returns the runtime type of the object, not the static type. There is no casting involved here.
This seems to me as if getClass() returns the dynamic (runtime) type of an object, while generics deals only with static (compile-time) type information.
What you print on the console is the actual, dynamic types.
However, in your example code, T would be type Object, therefore t = item is a perfectly valid assignment.

Categories

Resources