这篇文章写得还不错:
概述:
1.Collections(注意不是Collection,而是Collections,多了一个s)
2.它是一个集合工具类
3.方法分类:常规操作(查找,最大,最小等)、排序、线程安全(同步)操作、不可变集合
可以看看。
自己简单代码试验:
package cn.itcast.demo;
import java.util.*;
import org.junit.Test;
class Student1 implements Comparable{
private int age;
private String name;
private Integer score;
public Student1(int age,String name,int score)
{
this.age = age;
this.name = name;
this.score = score;
}
public int getAge(){
return this.age;
}
public int getScroe(){
return this.score;
}
//要显示Student类的信息,必须重写toString 方法
public String toString(){
return "age :"+age+" name:"+name;
}
public int hashCode()
{
return age*name.hashCode();
}
public boolean equals(Object o){
Student1 s = (Student1) o;
return age == s.age && name.equalsIgnoreCase(s.name);
}
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
Student1 s = (Student1) o;
int i = s.getAge() - this.age;
return i;
}
}
//Collections 类是一个工具类,用来对集合进行操作,它主要提供一些排序的算法,包括随机排序,反向排序等
public class CollectionsTest {
public static void printView(List arrayList)
{
Iterator it = arrayList.iterator();
while(it.hasNext())
{
System.out.print(" "+it.next());
}
System.out.println("");
}
@Test
public void CollectionsTest()
{
List list = new ArrayList();
Student1 stu1 = new Student1(18,"zxx",85);
Student1 stu2 = new Student1(23,"zxx",81);
Student1 stu3 = new Student1(26,"zxx",92);
Student1 stu4 = new Student1(25,"zxx",76);
list.add(stu1);
list.add(stu2);
list.add(stu3);
list.add(stu4);
System.out.print("初始化List内容:");
printView(list);
Collections.shuffle(list);
System.out.print("混淆后List内容:");
printView(list);
//list对象中的Student类要实现Comparable接口才能使用Sort方法
Collections.sort(list);
System.out.print("排序后List内容:");
printView(list);
Collections.reverse(list);
System.out.print("逆序后List内容:");
printView(list);
System.out.println("最小的::"+Collections.max(list));
List newlst = new ArrayList(Arrays.asList(new Object[list.size()]));
Collections.copy(newlst, list);
System.out.print("复制后List内容:");
printView(newlst);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}