2

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?

antimatter
  • 2,832
  • 2
  • 20
  • 31
  • There are ways of doing this, but you should think seriously about whether it's a good idea. Why don't you want to use collections? See http://stackoverflow.com/questions/1817524/generic-arrays-in-java – drew moore May 14 '14 at 05:03
  • @Chthonic - Ah sorry, that was a typo. Shouldn't be coding when I'm tired. – antimatter May 14 '14 at 05:57
  • @drewmore - Trying to get a very small performance boost on the algo. Others reported it helped. – antimatter May 14 '14 at 05:58
  • http://stackoverflow.com/questions/15867959/which-is-the-best-way-to-reduce-complexity-of-time-and-space-in-java/15867974#15867974 – drew moore May 14 '14 at 07:39
  • I agree with that post, but normally I don't worry about optimization so much. I'm comparing optimized mergesort algorithms in several languages, that's why I'm trying to get small performance benefits. – antimatter May 14 '14 at 13:02

1 Answers1

2

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;
    }
}
Hirak
  • 3,461
  • 1
  • 19
  • 32
  • @Chthonic - Sorry, wasn't trying to compare lists, I'm just tired and messed up my example code. Thanks Hirak. I tried using ``Array.newInstance`` earlier but it wasn't working. I guess I shouldn't code tired. – antimatter May 14 '14 at 05:59