Java's custom sorting methods for collections are:
Arrays.sort(T[],Comparator<? super T> c);
Collections.sort(List<T> list,Comparator<? super T> c);
Record the pair here Comparator's own understanding.
Demo code is as follows:
1. Entity class code:
class SortObj {
String letter;
int num;
public SortObj(String letter, int num) {
this.letter = letter;
this.num = num;
}
}
2. Comparator implementation code, The two classes are:
/**
* Character sorting (# comes last)
*/
class StrComparator implements Comparator<SortObj> {
@Override
public int compare(SortObj o1, SortObj o2) {
if("#".equals(o1.letter) && "#".equals(o2.letter)){
return 0;
}else if("#".equals(o1.letter)){
return 1;
}else if("#".equals(o2.letter)){
return -1;
}
return o1.letter.compareTo(o2.letter);
}
}
/**
* 数字排序 (升序)
*/
class NumComparator implements Comparator<SortObj> {
@Override
public int compare(SortObj o1, SortObj o2) {
if(o1.num > o2.num){
return 1;
}else if(o1.num < o2.on one){
return -1;
}else{
return 0;
}
}
}
3.调用排序并展示:
findViewById(R.id.btn_num_sort).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collections.sort(dataNum, new NumComparator());
printInfo(dataNum);
}
});
findViewById(R.id.btn_str_sort).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Collections.sort(dataStr, new StrComparator());
printInfo(dataStr);
}
});
display the result as follows:
Number sorting:
SortTest: (b,1) (r,2) (a,2) (a,3) (#,4) (#,5)
Character sorting :
SortTest: (a,3) (a,2) (b,1) (r,2) (#,4) (#,5)
The sorting algorithm is executed in the compare: the
returned results are 3 kinds: positive integer (1 ), negative integer (-1), 0
's own understanding of the returned result (
purely my own opinion
):
This is a bit of a bubble sort. When it is a positive integer, swap the positions of o1 and o2, when it is a negative integer. , do not change positions
Use of Comparator custom sorting
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=326201289&siteId=291194637
Ranking