java集合之——List的三种遍历方式

一、使用 iterator(迭代器)遍历

        1) java iterrator用于遍历集合,本身并不存放对象。

        2)迭代器iterator的基本操作:

                      iterator.hasNext():判断集合中是否有元素

                      iterator.next():将下一个元素返回

                      iterator.remove(): 将迭代器返回的元素删除

public class CollectionIterator {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {
        List list = new ArrayList();

        list.add(new Fruit("苹果","红色",4));
        list.add(new Fruit("香蕉","黄色",2));
        list.add(new Fruit("橘子","橙色",3));

        //遍历list集合
        //生成list的迭代器
        Iterator iterator = list.iterator();
        //通过while循环遍历,判断下一个是否有元素
        while (iterator.hasNext()) {
            //返回下一个元素
            Object next =  iterator.next();
            System.out.println("next="+next);
        }
    }
}

二、使用增强for遍历 

        基本语法:for(元素类型  元素名,集合名或数组名){访问元素}

public class CollectionIterator {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {
        List list = new ArrayList();

        list.add(new Fruit("苹果","红色",4));
        list.add(new Fruit("香蕉","黄色",2));
        list.add(new Fruit("橘子","橙色",3));

        for (Object fruit : list) {
            System.out.println("fruit="+fruit);
        }
    }
}

三、使用普通for遍历

        将价格从小到大排序,并用for循环遍历

    //冒泡排序
    public static void sort(List list){
        for (int i = 0; i < list.size() - 1; i++) {
            for (int j = 0; j < list.size()-1-i; j++) {
                //获取对象,向下转型
                Fruit fruit1= (Fruit) list.get(j);
                Fruit fruit2 = (Fruit)list.get(j + 1);
                if (fruit1.getPrice()>fruit2.getPrice()){
                    //交换
                    list.set(j,fruit2);
                    list.set(j+1,fruit1);
                }
            }
        }
    }
}
public class CollectionIterator {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {
        List list = new ArrayList();

        list.add(new Fruit("苹果","红色",4));
        list.add(new Fruit("香蕉","黄色",2));
        list.add(new Fruit("橘子","橙色",3));

        //排序前
        for (Object fruit : list) {
            System.out.println(fruit);
        }

        Fruit.sort(list);
        System.out.println("========================================");
        //排序后
        for (Object fruit : list) {
            System.out.println(fruit);
        }
    }
}

 

你可能感兴趣的:(java,eclipse,java,list,jvm)