Using generics for arrays - java

Is it possible to use generics for arrays?

Arrays are already basic objects types, that is to say they're not a class that describes a collection of other objects like ArrayList or HashMap.
You cannot have an array of generified types either. The following is illegal in Java:
List<String>[] lists = new List<String>[ 10 ];
This is because arrays must be typed properly by the compiler, and since Java's generics are subject to type erasure you cannot satisfy the compiler this way.

I don't think this is possible because an array is a basic datatype.
But you can use a ArrayList to have something similar. In most of the cases using a collection of some kind pays of very well.

No. Arrays must have a compile-time type.

Have a look at this site. It should contain all generics related FAQs.
On a sidenote:
class IntArrayList extends ArrayList<Integer> { }
IntArrayList[] iarray = new IntArrayList[5];
If you subclass a generic object with a concrete type, that new class can be used
as array type.

Can you use it? Ofc.
Example:
public static <T> T[] mergeArrays(T[]... arrays) {
ArrayList<T> arrayList = new ArrayList<T>();
for (T[] array : arrays) {
arrayList.addAll(Arrays.asList(array)); //we steal the reflection from core libs
}
return arrayList.toArray(arrays[0]);//we steal the reflection from core libs
}
Is it a good idea? No. This code is just me playing around with generics. It led to a dark ally. You are better of using collections. They do what you want, and the syntax is prettier in the long run.

It's possible, but far from pretty. In general, you're better of using the Collections framework instead.
See Sun's Generics tutorial, page 15, for a detailed explanation.

If I ever want to, say, refactor the elements of an array to a better type, like from String to MyPairClass<String, Integer>, I tend to avoid the unchecked cast problem by making an empty subclass that "bakes in" the generic parameters, e.g.
class Maguffin {
private static class StringIntegerPair extends MyPairClass<String, Integer> {
private static final long serialVersionUID = 1L;
};
...
private final StringIntegerPair[] horribleOldArray;
...
This nested class will probably also need constructors that delegate up to the generic type's constructors, depending on what you do when adding new array elements. When passing the elements out of the enclosing class, just cast them up to the generic type:
...
MyPairClass<String, Integer> getSomethingFromTheArray(int index) {
return horribleOldArray[index];
}
...
}
All this being said, there should rarely be a need to do something like this if you are writing something new from scratch. The only real benefit of arrays over the Collections framework classes is that you can write them out as literals, and this will no longer be an advantage come next year when Java 8 is released.

Excerpt from Java Generics and collections.
Arrays reify their component types, meaning that they carry run-time information about the type of their components. This reified type information is used in instance tests and casts, and also used to check whether assignments into array components are permitted.
Therefore one is not allowed to have the suntax
new List<Integer>[10] ;
However the following is allowed
List<String>[] stringListArray=(List<String>[])new List[10];
Now this is not a really good practice. Such casts are not safe and should be avoided.
Which in general points to the fact that we should avoid using arrays of generic type.

If you mean having an array of List then the answer is no. new List<Number>[10] is illegal in java. questions like these could be answerable by searching it in Google alone or checking out the official Generics tutorial

Related

Parameter to pass in for type Class<T[]>

I am trying to make a generic Stack class as shown
public class Stack<T> {
public Stack(Class<T[]> type, int capacity) {
this.capacity = capacity;
array = type.cast(Array.newInstance(type,capacity));
}
}
but am unsure of what to put in for type when instantiating since I thought of doing
MyClass[] c = new MyClass[0];
myStack = new Stack<MyClass>(c.getClass(), 100);
however I get the following error of
Required type: Class <MyClass[]>
Provided: Class <capture of ? extends MyClass[]>
so I thought of using
c.getClass().cast()\
but I am unsure of what to put inside of cast() since it won't take
Class<MyClass[]>
now I am stuck.
The overall design of this implementation is brittle. We are mixing two language constructs: arrays and generics. These two constructs differ in two major ways: arrays are covariant and retained, while generics are invariant and erased (see this question by eagertoLearn as to why). Mixing both is a recipe for disaster.
Furthermore, we need the component type to call Array::newInstance. Right now, we pass along the container-type.
I would recommend to use an Object[] as backing data structure and make the accessors generic to guarantee type-safety. This is also the approach taken by ArrayList. This approach will result in (at least) one unchecked cast that cannot be avoided. I leave it to the reader to
find the unchecked cast in ArrayList
argue why the cast is rectified and will never result in an actual ClassCastException as long as the interal array is never leaked.
You can refer to a typed array by adding [] after the class name:
myStack = new Stack<MyClass>(MyClass[].class, 100);

Java - is an array of type Class<? extends MyType> possible?

I've just been diving into Java generics and have come across something puzzling. I have a List of Class objects. These Class objects are of classes that extend the class MyType. What I want to do is the following:
Class<? extends MyType>[] myArray = myList.toArray( Class<? extends MyType>[] );
Now I know this won't work. But how is it possible to create such an array? My trouble is that I need to pass this List as a Class array to a method. I'd rather avoid #SuppressWarnings and figure out if it's possible.
You can pass the list as such but not instantiate as such. Must be instanced with concrete class substitutiona but then be assigned to whatever the captures.
There is rule "don't mess arrays with generics". There is the restriction in Java that states that creation of arrays of parameterized types is not allowed. So, the answer for your question is no, you can't create an array of any generic types.
UPD: Consider using any collection type instead of arrays. They will work just fine.
Or you can (but better not do that though) use array of non-generic elements and then cast them to appropriate type, suppressing warnings.
You have to provide the concrete type here which you also should know because of the type of myList.

Creating a generic array instance in a generic method

I'm trying to build a helper method to turn the two line list to array conversion into a single line. The problem I've ran into is that I'm not sure how to create a a T[] instance.
I've tried
Array.newInstance(T.class, list.size) but I can't feed it T.class..
Also tried new T[](list.size) but it doesn't like the parameters.
public <T> T[] ConvertToArray(List<T> list)
{
T[] result = ???
result = list.toArray(result);
return result;
}
Any other ideas?
Thanks
You can't mix generics and arrays like that. Generics have compile-time checking, arrays have runtime checking, and those approaches are mostly incompatible. At first I suggested this:
#SuppressWarnings("unchecked")
public <T> T[] ConvertToArray(List<T> list)
{
Object[] result = new Object[list.size()];
result = list.toArray(result);
return (T[])result;
}
This is wrong in a stealthy way, as at least one other person on here thought it would work! However when you run it you get an incompatible type error, because you can't cast an Object[] to an Integer[]. Why can't we get T.class and create an array the right type? Or do new T[]?
Generics use type erasure to preserve backward compatibility. They are checked at compile time, but stripped from the runtime, so the bytecode is compatible with pre-generics JVMs. This means you cannot have class knowledge of a generic variable at runtime!
So while you can guarantee that T[] result will be of the type Integer[] ahead of time, the code list.toArray(result); (or new T[], or Array.newInstance(T.class, list.size());) will only happen at runtime, and it cannot know what T is!
Here's a version that does work, as a reward for reading that lecture:
public static <T> T[] convertToArray(List<?> list, Class<T> c) {
#SuppressWarnings("unchecked")
T[] result = (T[]) Array.newInstance(c, list.size());
result = list.toArray(result);
return (T[]) result;
}
Note that we have a second parameter to provide the class at runtime (as well as at compile time via generics). You would use this like so:
Integer[] arrayOfIntegers = convertToArray(listOfIntegers, Integer.class);
Is this worth the hassle? We still need to suppress a warning, so is it definitely safe?
My answer is yes. The warning generated there is just an "I'm not sure" from the compiler. By stepping through it, we can confirm that that cast will always succeed - even if you put the wrong class in as the second parameter, a compile-time warning is thrown.
The major advantage of doing this is that we have centralised the warning to one single place. We only need to prove this one place correct, and we know the code will always succeed. To quote the Java documentation:
the language is designed to guarantee that if your entire application has been compiled without unchecked warnings using javac -source 1.5, it is type safe[1]
So now rather than having these warnings all over your code, it's just in one place, and you can use this without having to worry - there's a massively reduced risk of you making a mistake by using it.
You may also want to look at this SO answer which explains the issue in more depth, and this answer which was my crib sheet when writing this. As well as the already cited Java documentation, another handy reference I used was this blog post by Neal Gafter, ex senior staff engineer at Sun Microsystems and co-designer of 1.4 and 5.0's language features.
And of course, thanks to ShaneC who rightly pointed out that my first answer failed at runtime!
If you can't pass in T.class, then you're basically screwed. Type erasure means you simply won't know the type of T at execution time.
Of course there are other ways of specifying types, such as super type tokens - but my guess is that if you can't pass in T.class, you won't be able to pass in a type token either. If you can, then that's great :)
The problem is that because of type erasure, a List does not know it's component type at runtime, while the component type is what you would need to create the array.
So you have the two options you will find all over the API:
pass in the Array's component class (as suggested by Jon Skeet) or
create an Object[] array and cast it (as suggested by ZoFrex)
The only other possibility I can think of would be a huge hassle:
Iterate over all items of the list and find the "Greatest Common Divisor", the most specific class or interface that all the items extend or implement.
Create an array of that type
But that's going to be a lot more lines than your two (and it may also lead to client code making invalid assumptions).
Does this really need to be changed to a one-liner? With any concrete class, you can already do a List to Array conversion in one line:
MyClass[] result = list.toArray(new MyClass[0]);
Granted, this won't work for generic arguments in a class.
See Joshua Bloch's Effective Java Second Edition, Item 25: Prefer lists to array (pp 119-123). Which is part of the sample chapter PDF.
Here's the closest I can see to doing what you want. This makes the big assumptions that you know the class at the time you write the code and that all the objects in the list are the same class, i.e. no subclasses. I'm sure this could be made more sophisticated to relieve the assumption about no subclasses, but I don't see how in Java you could get around the assumption of knowing the class at coding time.
package play1;
import java.util.*;
public class Play
{
public static void main (String args[])
{
List<String> list=new ArrayList<String>();
list.add("Hello");
list.add("Shalom");
list.add("Godspidanya");
ArrayTool<String> arrayTool=new ArrayTool<String>();
String[] array=arrayTool.arrayify(list);
for (int x=0;x<array.length;++x)
{
System.out.println(array[x]);
}
}
}
class ArrayTool<T>
{
public T[] arrayify(List<T> list)
{
Class clazz=list.get(0).getClass();
T[] a=(T[]) Array.newInstance(clazz, list.size());
return list.toArray(a);
}
}

Code explanation in Java

this morning I came across this code, and I have absolutely no idea what that means. Can anyone explain me what do these <T> represent? For example:
public class MyClass<T>
...
some bits of code then
private Something<T> so;
private OtherThing<T> to;
private Class<T> c;
Thank you
You have bumped into "generics". They are explained very nicely in this guide.
In short, they allow you to specify what type that a storage-class, such as a List or Set contains. If you write Set<String>, you have stated that this set must only contain Strings, and will get a compilation error if you try to put something else in there:
Set<String> stringSet = new HashSet<String>();
stringSet.add("hello"); //ok.
stringSet.add(3);
^^^^^^^^^^^ //does not compile
Furthermore, another useful example of what generics can do is that they allow you to more closely specify an abstract class:
public abstract class AbstClass<T extends Variable> {
In this way, the extending classes does not have to extend Variable, but they need to extend a class that extends Variable.
Accordingly, a method that handles an AbstClass can be defined like this:
public void doThing(AbstClass<?> abstExtension) {
where ? is a wildcard that means "all classes that extend AbstClass with some Variable".
What you see here is something called Generics. They were introduced to Java in release 1.5.
You can read about them here and here. Hope this helps.
Imagine you're writing a List or Array class. This class must be able to hold elements of an unknown type. How do you do that?
Generics answers this question. Those <T> you're seeing can be read as some type. With generics you can write class MyList<T> { ... }, which in this context means a list that holds some type.
As an usage example, declare a list to store integers, MyList<Integer> listOfInts, or strings, MyList<String> listOfStrings, or one class you've written yourself MyList<MyClass> listOfMyClass.
What you are seeing is Java generics, which allows classes and methods to be parameterized by other classes. This is especially useful when creating container classes, since it saves you having to create separate classes for "a list of integers", "a list of strings", etc. Instead, you can have a single "list of some type T, where T is a variable" and then you can instantiate the list for some specific type T. Note that Java generics is not quite the same as template types in C++; Java generics actually use the same class definition but add implicit casting (generated by the compiler) and add additional type-checking. However, the different instantiations actually make use of the same exact type (this is known as erasure), where the parameterized types are replaced with Object. You can read more about this at the link.
Since noone has mentioned it yet, there is a very comprehensive guide/FAQ/tutorial on generics which can be found on Angelika Langer's site.

Making a generic parameterized type of anything

So I am trying to make a parameterized type that will work for anytype in Java this includes anything that is an object, and also the primitives types. How would i go about doing this?
Ok, suppose I want the target of a for-each to be a primitive, so its
for(int i : MyClass)
something like that. Is this possible to do?
Going from your comment on Bozho's answer, you probably want something like this:
interface MyInterface<T> extends Iterable<T> {
}
and no, you can't do that for primitive types. You could simulate an iterator for a primitive type, but it will never really be Iterable, as in, usable in a for-each loop.
I may be missing something but why don't you just implement Iterable<T>?
public MyClass<E>
it doesn't include primitive types, i.e. you can't declare MyClass<int> myobj;, but you can use the wrappers (java.lang.Integer, etc)
You can't do this sort of thing, usefully, for primitive types. If you are 'lucky' you get evil autoboxing, and if you are unlucky you might get protests from the compiler. If you look at GNU Trove or Apache Commons Primitives, you'll see the parallel universe that results from the desire to do the equivalent of the collections framework on primitive types.
I suppose that if you are sure that the overhead of autoboxing is acceptable to you it might make sense, but I can't get over my tendency to find it revolting.
This should work, but I suspect it is not what you are really after...
final List< Integer> list;
...
for(final int i : list)
{
}

Categories