Java的List中ArrayList的使用

public class Teacher implements Comparable{
 private String name;
 private int salary;

 public Teacher(String name, int salary) {
  this.name = name;
  this.salary = salary;
 }
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getSalary() {
  return salary;
 }
 public void setSalary(int salary) {
  this.salary = salary;
 }

 @Override
 public String toString() {
  return this.name+":"+this.salary;
 }

 public int compareTo(Object o) {
  
  if(o instanceof Teacher){
   Teacher teacher = (Teacher)o;
   return this.getSalary()-teacher.getSalary();
  }
  return 0;
 }

 @Override
 public boolean equals(Object obj) {
  //System.out.println("in equals...");
  if(this == obj){
   return true;
  }
  if(obj == null){
   return false;
  }
  if(obj instanceof Teacher){
   Teacher t1 = (Teacher) obj;
   return t1.getName().equals(this.getName());
  }
  return false;
 }

 
 public int hashCode() {
  //System.out.println("in hashCode...");
  return name.hashCode();
 }
 
}

 

 

public class TestList {

 @SuppressWarnings("unchecked")
 public static void main(String[] args) {
  List list = new ArrayList();
  
  list.add(new Teacher("haitao",50));
  list.add(new Teacher("xubin",60));
  list.add(new Teacher("wangwei",50000));
  list.add(new Teacher("haitao",50));
 
  Collections.sort(list);//Collections工具类用于排序

  Iterator it = list.iterator();
  while(it.hasNext()){
   System.out.println(it.next());
  }
  
 }

}

posted on 2013-05-12 19:41  Sunny_NUAA  阅读(264)  评论(0)    收藏  举报

导航