List排序 Collections.sort 实现Comparable接口

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

public class Test {

 public static void main(String[] args) {
  List<Person> persons=new ArrayList<Person>();
  initList(persons);
  
  show(persons);
  Collections.sort(persons);
  show(persons);
 }
 
 static void initList(List persons){
  Person p=new Person();
  p.setAge(1);
  p.setName("baby");
  persons.add(p);
  
  p=new Person();
  p.setAge(11);
  p.setName("kid");
  persons.add(p);
  
  p=new Person();
  p.setAge(51);
  p.setName("gather");
  persons.add(p);
  
  p=new Person();
  p.setAge(21);
  p.setName("father");
  persons.add(p);
 }

 static void show(List persons){
  Person p=null;
  for(int i=0;i<persons.size();i++){
   p=(Person)persons.get(i);
   
   System.out.println("name = "+ p.getName()+ ", age="+p.getAge());//按插入的顺序
  }
 }
}

 

package list;

public class Person implements Comparable {

 private String name;
 private int age;
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }

 public int compareTo(Object o) {
  if(!(o instanceof Person)){
   return -1;
  }
  
  Person p=(Person)o;
  if(this.age==p.getAge()){
   return 0;
  }
  else if(this.age>p.getAge()){
   return 1;
  }
  else{
   return -1;
  }
  
 }
 
 
 
}

 

   使用工具类Collections实现List的排序,其中的对象必须实现Comparable接口 

 

Person pp=null;
  Iterator it=persons.iterator();
  while(it.hasNext()){
   pp=(Person)it.next();
   System.out.println(pp.getName());
  }
  

Person p1=new Person();
  p1.setName("kid22");
  p1.setAge(11);
  int i=Collections.binarySearch((List)persons, p1);   //依赖Comparable接口
  System.out.println("i="+i);

 

Collections.reverse(persons);   //反序

 

persons=Collections.emptyList(); // 清空list

 

Person p=Collections.max(persons);

 

p=Collections.min(persons);

 

Collections.shuffle(persons);// 混洗

 

persons=Collections.synchronizedList(persons);

 

 

你可能感兴趣的:(Collections)