Author | Message |
---|---|
jgarc659
Posts: 27
|
Posted 21:53 Jan 30, 2018 |
So I was able to get the removeDuplicates() method to work based on what was taught in class, except for one issue. I created the outbound array as such: E[] outList = (E[])new Comparable[finalLength]; When I try storing this returned array (of strings) from the main method, however, it will only work if I phrase it like this: Comparable<String>[] newList2 = removeDuplicates(list2); When I try storing it as a String array, like this: String[] newList2 = removeDuplicates(list2); I get the following error message: Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Comparable; cannot be cast to [Ljava.lang.String; Is there a way around this issue? Or would it be acceptable to leave it as-is? Last edited by jgarc659 at
22:25 Jan 30, 2018.
|
buensons
Posts: 5
|
Posted 22:16 Jan 30, 2018 |
The only way I found it to work is to add Class object as one of the method's argument public static <E extends Comparable<E>> E[] removeDuplicates(Class class1, E[] list) Then instantiate array you want to return like this: E [] nonDuplicateArray = (E[]) Array.newInstance(class1, count); When you calling the method in main, just give it class argument depending on what data type you use. example for Integer: removeDuplicates(Integer.class, myArray); |
jgarc659
Posts: 27
|
Posted 22:31 Jan 30, 2018 |
That's a clever approach, I just implemented it and it's the only one that seems to work for me too. I'm not certain this is the approach we were intended to take though, as the method signature was specified as removeDuplicates(E[] list). Hopefully this can be cleared up soon. |
smallch
Posts: 10
|
Posted 23:07 Jan 30, 2018 |
I hope so, I managed to make it kinda work by moving the duplicates away and counting only the non duplicates. But that only worked with integers and is pretty inefficient. |