12

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

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
Shane Courtrille
  • 13,960
  • 22
  • 76
  • 113

5 Answers5

14

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!

Community
  • 1
  • 1
ZoFreX
  • 8,812
  • 5
  • 31
  • 51
  • The problem with this one is that if you call it Integer[] results = convertToArray(listOfIntegers) you'll get an error that you can't cast java.lang.Object to java.lang.Integer – Shane Courtrille Dec 02 '10 at 17:13
  • ShaneC is correct, this doesn't work. Sorry, I didn't have a Java compiler to hand when I wrote this! – ZoFreX Dec 02 '10 at 20:57
2

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 :)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • That just seems like such overkill to me.. *sigh* – Shane Courtrille Dec 02 '10 at 16:28
  • @Ed: Fixed, thanks. @ShaneC: Type erasure sucks, basically... particularly if you're used to .NET's very different implementation of generics. – Jon Skeet Dec 02 '10 at 16:30
  • @Jon Skeet give me a cross platform / open source version of C# without Microsoft anywhere around and I'll jump on it in an instant – Sean Patrick Floyd Dec 02 '10 at 16:39
  • @S.P.Floyd: Have you looked at Mono? – Jon Skeet Dec 02 '10 at 17:07
  • @Jon Skeet sure, some years ago (it looked pretty rough back then). Should probably check it out again some time – Sean Patrick Floyd Dec 02 '10 at 17:11
  • It's not as limiting as many people say or think! See my answer for a way to get around this problem. Personally I rarely have problems from type erasure in practice (although I did before I hit the books). – ZoFreX Dec 02 '10 at 21:16
  • @ZoFreX: Personally I still find it a massive pain in the backside, when compared with .NET's generics. Java generics would have been *much* better without type erasure. – Jon Skeet Dec 02 '10 at 21:32
1

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:

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).

Community
  • 1
  • 1
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • Please note that my way won't work, so there's only one option! – ZoFreX Dec 02 '10 at 20:58
  • Update: Fixed my way, but it is now the same as Jon Skeet's answer. Still only one option. – ZoFreX Dec 02 '10 at 21:15
  • This method has the problem that a `List` that happens to only contain `Cat` instances will mean you return a `Cat[]` instead of `Animal[]`, causing some other code to fail when it tries to stick a `Dog` into the resulting array. – Gabe Dec 02 '10 at 21:21
  • I know, that's precisely what I meant in my last sentence. – Sean Patrick Floyd Dec 02 '10 at 21:35
0

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.

Powerlord
  • 87,612
  • 17
  • 125
  • 175
-1

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);
  }
}
Jay
  • 26,876
  • 10
  • 61
  • 112