[JAVA]容器

1、使用容器存储对象,并重写Comparable接口,使用Collections类的静态方法对容器进行处理.

package javaTest;
import java.util.*;
import static java.lang.System.out;

public class Hello implements Comparable<Hello>   {

    public int i=0;
    
    public Hello(int i){
        this.i=i;
    }
    
    //实现Comparable接口
    public int compareTo(Hello h){
        if(h.i==this.i)
            return 0;
        return h.i>this.i?-1:1;
    }
    
    //实现toString()方便打印
    public String toString(){
        return new String()+i;
    }


    public static void main(String[] args)
    {
        ArrayList<Hello> al=new ArrayList<Hello>();
        al.add(new Hello(3));
        al.add(new Hello(33));
        al.add(new Hello(2));
        al.add(new Hello(1));
        out.println(al);
        //使用Collections(不是Collection)的静态方法对容器进行排序和查找等工作
        Collections.sort(al);
        out.println(al);
    }

}
原文地址:https://www.cnblogs.com/iyjhabc/p/3473368.html