A problem was encountered if the list collection previously used was not sorted. All of a sudden, there's a collections.
This tool class, with Collections.sort (Spidermodel); Sort
list<spidermodel> Spidermodel = new arraylist<spidermodel> ();
Spidermodel.add (New Spidermodel ("1", 1, 20));
Spidermodel.add (New Spidermodel ("220", 2, 20));
Spidermodel.add (New Spidermodel ("31", 3, 20));
Collections.sort (Spidermodel); Here will be the compiler will prompt an error, tell us to implement comparable<t> this interface,
This writing will not error, and can be customized sorting, is not very good, but, business, often change, which day has changed the collation, you have to change the code,
Still have to go online, change to say no, but also change over, then you have to change, so look for there is no other way.
public class Spidermodel implements comparable<spidermodel>{
/**
* Order name
*/
Private String Spiderordername;
/**
* Current Page
*/
private int currentpage;
/**
* Total Pages
*/
private int totalpage;
Public Spidermodel (String spiderordername, int currentpage, int totalpage) {
Super ();
This.spiderordername = Spiderordername;
This.currentpage = CurrentPage;
This.totalpage = Totalpage;
}
Public String Getspiderordername () {
return spiderordername;
}
public void Setspiderordername (String spiderordername) {
This.spiderordername = Spiderordername;
}
public int getcurrentpage () {
return currentpage;
}
public void setcurrentpage (int currentpage) {
This.currentpage = CurrentPage;
}
public int gettotalpage () {
return totalpage;
}
public void settotalpage (int totalpage) {
This.totalpage = Totalpage;
}
@Override
public int compareTo (Spidermodel o) {
if (This.totalpage < O.gettotalpage ())
return-1;
else if (This.totalpage = = O.gettotalpage ())
Return This.spiderOrderName.compareTo (O.getspiderordername ());
Else
return 1;
}
}
Comparator this interface, can be compared, the Collections.sort (list) is changed to Collections.sort (list, new Spidercompare ());
It is OK, later changes only need to implement this interface, add new comparison rules on the line.
public class Spidercompare implements comparator<spidermodel>{
@Override
public int Compare (Spidermodel O1, Spidermodel O2) {
if (O1.gettotalpage () < O2.gettotalpage ())
return-1;
else if (O1.gettotalpage () < O2.gettotalpage ())
Return O1.getspiderordername (). CompareTo (O2.getspiderordername ());
Else
return 1;
}
}
If you feel that you write code, a very simple thing, if you write a lot of code, stop to think, so write right, my personal approach is that the leadership to my task, I will first think, think well in doing, think of the time will not delay progress.
Java Comparator and comparable