So first, I have an object called news article that has three properties that I need to sort by:
Year (int), Month (int), type (String - online, paper)
So for example, it would be like this:
- Online 2013 4
- Online 2013 1
- Online 2009 11
- Online 2008 4
- Paper 2012 12
- Paper 2011 9
What is going on is that the month and year appear to be sorting correctly, but I'm having problems sorting by type. What's the proper way to sort by String in a compareTo?
Results at the moment:
- Paper 2012 12
- Paper 2011 9
- Online 2013 4
- Online 2013 1
- Online 2009 11
- Online 2008 4
Here's my method (I apologize for it being somewhat quirky, I've been trying different ways to sort by the type and was experimenting):
@Override
public int compareTo(Article rs) {
Integer x = 0;
Integer year1 = 0;
Integer year2 = 0;
Integer month1 = 99999;
Integer month2 = 99999;
Integer type1 = 99999;
Integer type2 = 99999;
if(rs.year != null && year != null) {
if(!rs.year.equals(""))
year1 = Integer.parseInt(rs.year);
if(!year.equals(""))
year2 = Integer.parseInt(year);
}
if(rs.month != null && month != null) {
if(!rs.month.equals(""))
month1 = Integer.parseInt(rs.month);
if(!month.equals(""))
month2 = Integer.parseInt(month);
}
if(rs.type == null)
type1 = 99999;
else
type1 = 0;
if(type == null)
type2 = 99999;
else
type2 = 0;
x = type2.compareTo(type1);
if(x != 0) {
return x;
}
x = year1.compareTo(year2);
if(x != 0) {
return x;
}
x = month1.compareTo(month2);
if(x != 0) {
return x;
}
return x;
}
typealphabetical or a specialized sort order that you are attempting to define?