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

本文介绍了迭代器的基本工作原理及如何使用迭代器遍历容器中的元素。通过具体示例展示了如何利用迭代器来访问ArrayList中存储的对象,并进一步讲解了如何通过Collections类对容器中的对象进行排序。

迭代器方法:
这里写图片描述
迭代器的工作原理:
这里写图片描述
注意:迭代器是指向两个元素之间的位置,如果后面有元素则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=xiaohong
num=3, name=xiaozhu
num=5, name=xiaoxi
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值