ArrayList中元素排序方法：Collections.sort(list)

ArrayList中元素排序方法：Collections.sort(list)

package cccc;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SortTest {

public static void main(final String[] args) {
final List<String> lists = new ArrayList<String>();
final List<A> list = new ArrayList<A>();
final List<B> listB = new ArrayList<B>();
// lists中的对象String 本身含有compareTo方法，所以可以直接调用sort方法，按自然顺序排序，即升序排序
Collections.sort(lists);

final A aa = new A();
aa.setName("aa");
aa.setOrder(1);
final A bb = new A();
bb.setName("bb");
bb.setOrder(2);
// list中的对象A实现Comparable接口
Collections.sort(list);

final B ab = new B();
ab.setName("ab");
ab.setOrder("1");
final B ba = new B();
ba.setName("ba");
ba.setOrder("2");
// 根据Collections.sort重载方法来实现
Collections.sort(listB, new Comparator<B>() {

@Override
public int compare(final B b1, final B b2) {
return b1.getOrder().compareTo(b2.getOrder());
}

});

System.out.println(lists);
System.out.println(list);
System.out.println(listB);

}

}

class A implements Comparable<A> {

private String name;

private Integer order;

public String getName() {
return name;
}

public void setName(final String name) {
this.name = name;
}

public Integer getOrder() {
return order;
}

public void setOrder(final Integer order) {
this.order = order;
}

@Override
public String toString() {
return "name is " + name + " order is " + order;
}

@Override
public int compareTo(final A a) {
return order.compareTo(a.getOrder());
}

}

class B {

private String name;

private String order;

public String getName() {
return name;
}

public void setName(final String name) {
this.name = name;
}

public String getOrder() {
return order;
}

public void setOrder(final String order) {
this.order = order;
}

@Override
public String toString() {
return "name is " + name + " order is " + order;
}
}


©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客