I tried to write a generic class to sort a array of any type.
First sort function does sorting of any type of array.
Its working fine.
In second sort function, I passed list and tried to convert into array to use first sort function. But when i tried to convert list into array inside generic class, It throws unexpected type error.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Sort<T extends Comparable>{
//public T l;
T tmp;
public void sort(T[] l){
for(int i=0;i<l.length;i++){
for(int j=i+1;j<l.length;j++){
if(l[i].compareTo(l[j])>0){
tmp=l[i];
l[i]=l[j];
l[j]=tmp;
}
}
}
System.out.println( Arrays.asList(l));
}
public <T extends Comparable> void sort(List<T> l){
T[] array = (T[]) new Object[l.size()];
sort(l.toArray(T[] array));
// System.out.println(l);
}
public static void main(String[] args){
Integer[] i={2,4,1,5,3};
List<String> l = Arrays.asList("c","d","a","e","b");
Sort s=new Sort();
//String[] j=l.toArray(new String[l.size()]);
s.sort(i);
s.sort(l);
}
}