java-集合类(二)-迭代器-Iterator-Collections类自然排序

来源:互联网 发布:mac word转pdf 白边 编辑:程序博客网 时间:2024/06/05 06:43

迭代器方法:
这里写图片描述
迭代器的工作原理:
这里写图片描述
注意:迭代器是指向两个元素之间的位置,如果后面有元素则hasNext()返回真,当我们调用next()方法时,返回黄色的元素,如上图,当我们调用remove方法是要先调用一次next(),调用remove将返回的元素删除.
容器的最大作用实例:

package ArrayList;import java.util.ArrayList;import java.util.Arrays;import java.util.Collection;import java.util.Iterator;import java.util.List;class ArrayListTest {    //容器的最大作用    public static void printElements(Collection c){        Iterator it = c.iterator();        while(it.hasNext()){            System.out.println(it.next());        }    }    public static void main(String[] args)    {        ArrayList al = new ArrayList();        al.add(new Point(3,3));        al.add(new Point(4,4));        printElements(al);    }}class Point{    int x,y;    Point(int x,int y){        this.x = x;        this.y = y;    }    public String toString(){        return "x=" + x +","+"y=" + y;    }}

Collections类
排序:Collections.sort()
(1)自然排寻(natural ordering );
(2)实现比较器(Comparator)接口。

package ArrayList;import java.util.ArrayList;import java.util.Arrays;import java.util.Collection;import java.util.Collections;import java.util.Iterator;import java.util.List;class ArrayListTest {    public static void printElements(Collection<?> c) {        Iterator<?> it = c.iterator();        while(it.hasNext()){            System.out.println(it.next());        }    }    public static void main(String[] args) {        Student s1 = new Student(5, "xiaoxi");        Student s2 = new Student(2, "xiaohong");        Student s3 = new Student(3, "xiaozhu");        ArrayList<Student> al = new ArrayList<Student>();        al.add(s1);        al.add(s2);        al.add(s3);        //Collections类进行排序,自然排序        Collections.sort(al);        printElements(al);    }}class Student implements Comparable<Object> {    int num;    String name;    Student(int num, String name) {        this.name = name;        this.num = num;    }    @Override    public int compareTo(Object arg0) {        Student s = (Student) arg0;        //如果当前数比你要比较的数大返回1,小,返回负数        return num > s.num ? 1 : (num == s.num ? 0 : -1);    }    public String toString() {        return "num=" +num + ", name=" + name;    }}

结果

num=2, name=xiaohongnum=3, name=xiaozhunum=5, name=xiaoxi
0 0
原创粉丝点击