1. 程式人生 > >比較set()與add()方法的差異

比較set()與add()方法的差異

package my;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class CollectiongDemo {
    public static void main(String[] args){
        String a="A", b = "B", c = "C", d = "D", e = "E";
        List<String> list=new LinkedList<String>();
        list.add(a);
        list.add(e);
        list.add(d);
        Iterator<String> firstIterator=list.iterator();
        System.out.println("修改前集合中的元素是:");
        while (firstIterator.hasNext()){
            System.out.println(firstIterator.next()+" ");
        }
        list.set(1,b);
        list.add(2,c);
        Iterator<String> it = list.iterator();
        System.out.println();
        System.out.println("修改後集合中的元素是:");
        while (it.hasNext()){
            System.out.println(it.next()+"  ");
        }
    }
}
效果如下: