java--集合输出


集合输出有四种方式:Iterator,ListIterator,foreach,Enumeration,

集合就用Iterator


public class test {
    public static void main(String args[]) throws Exception {
        Set all = new HashSet();
        all.add("A");
        all.add("B");
        all.add("B");
        Iterator iter = all.iterator();
        while(iter.hasNext()){
            String str = iter.next();
            System.out.println(str);
        }
    }
}


ListIterator专门为List定义的双向迭代


public class test {
    public static void main(String args[]) throws Exception {
        List all = new ArrayList<>();
        all.add("A");
        all.add("B");
        all.add("B");
        ListIterator iter = all.listIterator();
        System.out.print("由前向后输出:");
        while(iter.hasNext()){
            String str = iter.next();
            System.out.print(str + ',');
        }
        System.out.print("\n由后向前输出:");
        while(iter.hasPrevious()){
            System.out.print(iter.previous() + ',');
        }
    }
}



Enumeration适用于Vector
public boolean hasMoreElements(); //判断是否有下一个元素 等同于hasNext()
public E nextElement();//取出下一个元素 等同于next()


public class test {
    public static void main(String args[]) throws Exception {
        Vector all = new Vector<>();
        all.add("A");
        all.add("B");
        all.add("B");
        Enumeration iter = all.elements();
        while(iter.hasMoreElements()){
            System.out.println(iter.nextElement());
        }
    }
}










你可能感兴趣的:(java)