Collections 有sort方法,但是如果list中保存的是一个自定义的对象,就需要自己来写排序的方法了,重写Comparator
方法,实现自己的不同对象比较方法
自定义对象:
package com.java.datastructure; public class Peo { private String name; private int age; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if(this == obj) return true; if(obj == null) return false; if(getClass() != obj.getClass()) return false; Peo other = (Peo) obj; if(name == null) { if(other.name != null) return false; } else if(!name.equals(other.name)) return false; return true; } public Peo() { } public Peo(String name) { this.name = name; } 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; } }
测试方法:
package com.java.datastructure; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Set; public class T2 { public static void main(String[] args) { t1(); } static void t1(){ boolean flag ; List<Peo> list = new ArrayList<Peo>(); Peo peo = new Peo("j"); peo.setAge(100); list.add(peo); Peo peo2 = new Peo("m"); peo2.setAge(79); list.add(peo2); Peo peo3 = new Peo("m"); peo3.setAge(200); list.add(peo3); for(Peo p:list){ System.out.println(p.getAge()); } System.out.println("-------------------------------"); Collections.sort(list, new Comparator<Peo>() { @Override public int compare(Peo o1, Peo o2) { return new Integer(o1.getAge()).compareTo(new Integer(o2.getAge())); } }); for(Peo p:list){ System.out.println(p.getAge()); } } }打印的结果为:
100 79 200 ------------------------------- 79 100 200