سؤال

Is it possible to create a new generic array that implements comparable?

I have something like:

public class MyClass<T extends Comparable<T>> {
    ...
    public T[] myAlgorithm( T[] list1, T[] list2 ) {
        T[] newList = (T[]) new Object( ... );

        if ( list1[0].compareTo( list2[0] ) < 0 ) {
            ...
        }

        return newList;
    }
}

But it (obviously) throws the error:

[Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable

I create a new instance of the Object class (the parent of all classes) and cast it to the parameterized type to get the parameterized array. I read from other sources that this is the way to do it. But I want it to use comparable in the way my algo shows in the code, and I don't want to use a collection.

Any way to do something like this?

هل كانت مفيدة؟

المحلول

One way would be as below (untested code):

public class MyClass<T extends Comparable<T>> {
    public T[] myAlgorithm( T[] list1, T[] list2 ) {
        @SuppressWarnings("unchecked")
        T[] newList = (T[])Array.newInstance(list1[0].getClass(), list1.length);

        for (T t1 : list1) {
            for (T t2 : list2) {
                if(t1.compareTo(t2)==0) {
                    //TODO
                }
            }
        }

        return newList;
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top