JAVA中集合输出的四种方式

在JAVA中Collection输出有四种方式,分别如下:

一) Iterator输出。 该方式适用于Collection的所有子类。

public class Hello
{
    public static void main(String[] args) throws Exception
    {
        Set<Person> javaProgramers = new HashSet<Person>();
        javaProgramers.add(new Person("aaron",25));
        javaProgramers.add(new Person("larry", 32));
        javaProgramers.add(new Person("jesse", 33));
        javaProgramers.add(new Person("mike",65));
        javaProgramers.add(new Person("jesse",33));
        
        Iterator<Person> iter = javaProgramers.iterator();
        while(iter.hasNext())
        {
            System.out.println(iter.next());
        }
    }
}

二)foreach输出。该方式适用于Collection的所有子类。

public class Hello
{
    public static void main(String[] args) throws Exception
    {
        Set<Person> javaProgramers = new HashSet<Person>();
        javaProgramers.add(new Person("aaron",25));
        javaProgramers.add(new Person("larry", 32));
        javaProgramers.add(new Person("jesse", 33));
        javaProgramers.add(new Person("mike",65));
        javaProgramers.add(new Person("jesse",33));
        
        for(Person item:javaProgramers)
        {
            System.out.println(item);
        }
    }
}

三)ListIterator。仅适用于List接口的子类。

public class Hello
{
    public static void main(String[] args) throws Exception
    {
        List<Person> javaProgramers = new ArrayList<Person>();
        javaProgramers.add(new Person("aaron",25));
        javaProgramers.add(new Person("larry", 32));
        javaProgramers.add(new Person("jesse", 33));
        javaProgramers.add(new Person("mike",65));
        javaProgramers.add(new Person("jesse",33));
        
        ListIterator<Person> iter = javaProgramers.listIterator();
        System.out.println("正序输出:");
        while(iter.hasNext())
        {
            System.out.println(iter.next());
        }
        System.out.println("反序输出:");
        while(iter.hasPrevious())
        {
            System.out.println(iter.previous());
        }
    }
}

四)Enumeration输出。仅适用于Vector类。

public class Hello
{
    public static void main(String[] args) throws Exception
    {
        Vector<Person> javaProgramers = new Vector<Person>();
        javaProgramers.add(new Person("aaron",25));
        javaProgramers.add(new Person("larry", 32));
        javaProgramers.add(new Person("jesse", 33));
        javaProgramers.add(new Person("mike",65));
        javaProgramers.add(new Person("jesse",33));
        
        Enumeration<Person> enumeration = javaProgramers.elements();
        while(enumeration.hasMoreElements())
        {
            System.out.println(enumeration.nextElement());
        }
    }
}

 

posted on 2016-08-07 22:33  kuillldan  阅读(21617)  评论(0编辑  收藏  举报