1

I will get right into the problem here. This is the method that I have so far:

public T[] getAllValues() {
    Serializable[] result = new Serializable[sets.size()];
    for (int i = 0; i < sets.size(); i++) {
        result[i] = sets.get(i).getValue();
    }   
    return (T[]) result;
}

'T' is a parameterized type that extends Serializable. 'sets' is an ArrayList holding a type that stores both a String (key) and a T (value), so getValue() returns a T. In this method, I want to return all Ts in an array, so what I would actually like to do looks more like this:

public T[] getAllValues() {
    T[] result = new T[sets.size()];
    for (int i = 0; i < sets.size(); i++) {
        result[i] = sets.get(i).getValue();
    }
    return result;
}

So the Serializable array, that is casted to a T array was just an idea as a work-around, but does not work unfortunately. But at the same time, I cannot use the second version, because

new T[int];

is obviously not possible to construct when the type is parameterized. Why is that? And more importantly: How can I work around it?

Thank you in advance

EDIT: I solved the problem, this is what I came up with:

public T[] getAllValues(T[] typearray) {
    for (int i = 0; (i < typearray.length) && (i < sets.size()); i++) {
        typearray[i] = sets.get(i).getValue();
    }
    return typearray;
}
Tom S.
  • 233
  • 2
  • 9
  • 4
    In short: not possible to create generic arrays. See http://stackoverflow.com/questions/529085/java-how-to-generic-array-creation – Robin Dec 31 '11 at 16:39
  • @Tom About your solution in the edit: You should avoid using input arguments for output. It's quite confusing for other developers, or for future you. Returning the same array also adds to the confusion. – toto2 Dec 31 '11 at 18:16
  • @toto2 Of course, I understand what you mean, but what makes me keep using this solution is, besides the fact that I don't have any other ideas, that this is one of the minor methods in the API I'm making, which will only be used by more skilled developers, who will probably understand my documentation. Thank you for your ideas though. – Tom S. Dec 31 '11 at 22:22

1 Answers1

1

You should avoid using arrays in general and it won't work at all in this case.

Using List<T> (or Set<T>) instead of an array solves all your problems.

Aside comment:
I'm not sure what you are doing, but it seems that instead of having a sets that contains a list of pairs (String, T), you could have a Map<String, T>. You would not need your method getAllValue() since map.values() returns a Collections<T> of all T's.

toto2
  • 5,216
  • 19
  • 24