3

The idea is to do something like the below and have the compiler check at compile time that toLoad is an array that can contain AType objects (ie: AType extends or is a T NOT T extends or is AType). Is there a way to do this with generics?

private List<AType> aList_;

<T superclassof AType> T[] loadArray(T[] toLoad) {
    for(int i = 0; i < alist_.size(); ++i) {
        toLoad[i] = (T)aList_.get(i);
}
peterk
  • 5,136
  • 6
  • 33
  • 47
  • 1
    Not that I know of. Can you explain why you want to do this? – Code-Apprentice Mar 08 '13 at 00:08
  • possible duplicate of [Bounding generics with 'super' keyword](http://stackoverflow.com/questions/2800369/bounding-generics-with-super-keyword) – Paul Bellora Mar 08 '13 at 02:42
  • This is a *general* question - the above is to simply illustrate a valid potential desire :) That is an array may have any object assigned to it for which the array element type is a super class. ie: The " T[] toArray(T[] a)" method in java.util.List is not type checked at compile time, but can throw run time exceptions. – peterk Mar 09 '13 at 02:28

2 Answers2

4

Changing my answer. Yes there is a "super" keyword to use with generics, but I don't think it will work here.

Here is an explanation of how it is used: java generics super keyword

What you should probably do is return Collections.toArray() on the list and bind it to the type you are using (which could be generic itself). I don't think you really need to define the return type as being a superclass of anything.

Community
  • 1
  • 1
4

No... Java does not allow lower bounds on type variables, even though there are some valid use cases... like yours.

If you use List, we can use wildcard with lower bound List<? super A>. But not for arrays.

<L extends List<? super A> L load(L toLoad) 
{
    for(int i = 0; i < alist_.size(); ++i) 
        toLoad.set(i, aList_.get(i) );
    return toLoad;
}

We can wrap an array in a List though.

Object[] array = new Object[length];

load(new Wrapper<>(array));

class Wrapper<E> implements List<E>
{
    E[] array;

    Wrapper(E[] array){ this.array=array; }

    E set(int index, E element)
    {
        check index<array.length
        array[index] = element;
    }
irreputable
  • 44,725
  • 9
  • 65
  • 93