ArrayList类的测试

//ArrayList的测试

 

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

public class ArrayListTest
{
 public static void printElements(Collection c)
 {
  Iterator i = c.iterator();
  while (i.hasNext())
  {
   System.out.println(i.next());
  }
 }
 
    public static void main(String[] args)
 {
  Student s1 = new Student(12 , "zhangsan");
  Student s2 = new Student(11 , "wangwu");
  Student s3 = new Student(13 , "lisi");
  Student s4 = new Student(12 , "mybole");
  List<Student> l = new ArrayList<Student>();
  l.add(s1);
  l.add(s2);
  l.add(s3);
  l.add(s4);
  Collections.sort(l);
   Collections.sort(l,new Student.StudentComparator());
  // Collections.sort(l,Collections.reverseOrder());
//   Collections.frequency(c , o)
//   (o == null ? e == null : o.equals(e))
  printElements(l);
 }
}

class Student implements Comparable
{
 int    num;
 
 String name;
 
 
 static class StudentComparator implements Comparator
 {
  public int compare(Object obj1 , Object obj2)
  {
   Student st1 = (Student) obj1;
   Student st2 = (Student) obj2;
   int result = st1.num>st2.num ? 1 : (st1.num==st2.num ? 0 : -1);
   if (0==result)
   {
    result = st1.name.compareTo(st2.name);
   }
   return result;
  }
 }
 
 
 Student(int num , String name)
 {
  this.name = name;
  this.num = num;
 }
 
 public int compareTo(Object obj)
 {
  Student s = (Student) obj;
  return num>s.num ? 1 : (num==s.num ? 0 : -1);
 }
 
 public String toString()
 {
  return "num="+num+","+"name="+name;
 }
}

你可能感兴趣的:(java,C++,c,C#)