List接口,Collections类,Comparable接口

List接口的方法
Object get(int index)
Object set(int index, Object element); 将旧的元素返回
void add(int index, Object element); 全部往后退一格
Object remove(int index);
int indexOf(Object o); 用了equals方法
int lastIndexOf(Object o);

Collections类,提供了对List的一些常用方法,如排序,倒序等

Comparable接口,实现了的类可以互相比较大小,用于确定排序方式
public int compareTo(Object obj)
0 ==
+ >
- <
class Person implements Comparable;

 

public class wori
{
public static void main(String args[])
{
    List a = new LinkedList();
    for(int i = 5; i > 1; i--)
    {
        a.add(new Person(i));
    }
    Collections.sort(a);
    System.out.println(a);
}
}

class Person implements Comparable
{
    private int age;
    Person(int n)
    {
        age = n;
    }
    public int compareTo(Object o)
    {
        Person a = (Person)o;
        if(age == a.age)
        {
            return 0;
        }
        else if(age > a.age)
        {
            return 1;
        }
        else
        {
            return -1;
        }
    }
    public String toString()
    {
        return String.valueOf(age);
    }
}

 

posted on 2014-09-18 13:47  平庸  阅读(127)  评论(0编辑  收藏  举报

导航