I still have no idea what I'm doing with Generics. How do I get rid of the warning?
The latest warning message is: unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable
and the offending line of code:
return ((Comparable)c1).compareTo(c2);
The entire program:
import java.util.Comparator;
import java.util.List;
/**
* A comparator to sort Lists of data based on a column within each List
*/
public class ListComparator implements Comparator
{
private int column;
private boolean isAscending;
private boolean isNullsLast;
private boolean isIgnoreCase = false;
ListComparator(int column)
{
this(column, true);
}
ListComparator(int column, boolean isAscending)
{
this(column, true, true);
}
ListComparator(int column, boolean isAscending, boolean isNullsLast)
{
setColumn( column );
setAscending( isAscending );
setNullsLast( isNullsLast );
}
public void setColumn(int column)
{
this.column = column;
}
public void setAscending(boolean isAscending)
{
this.isAscending = isAscending;
}
public void setNullsLast(boolean isNullsLast)
{
this.isNullsLast = isNullsLast;
}
public void setIgnoreCase(boolean isIgnoreCase)
{
this.isIgnoreCase = isIgnoreCase;
}
public int compare(Object a, Object b)
{
List list1 = (List)a;
List list2 = (List)b;
Object o1 = list1.get(column);
Object o2 = list2.get(column);
// Treat empty strings like nulls
if (o1 instanceof String && ((String)o1).length() == 0)
{
o1 = null;
}
if (o2 instanceof String && ((String)o2).length() == 0)
{
o2 = null;
}
// Handle sorting of null values
if (o1 == null && o2 == null) return 0;
if (o1 == null) return isNullsLast ? 1 : -1;
if (o2 == null) return isNullsLast ? -1 : 1;
// Compare objects
Object c1;
Object c2;
if (isAscending)
{
c1 = o1;
c2 = o2;
}
else
{
c1 = o2;
c2 = o1;
}
if (c1 instanceof Comparable)
{
if (c1 instanceof String
&& isIgnoreCase)
return ((String)c1).compareToIgnoreCase((String)c2);
else
return ((Comparable)c1).compareTo(c2);
}
else // Compare as a String
{
return c1.toString().compareTo(c2.toString());
}
}
}