两个参数,第一个参数是要修改的元素的索引,第二个参数是要设置的新值。
案例一:当链表中传入的是字符串时:
- public static void main(String[] args) {
- List list = new LinkedList();
- list.add("鱼香肉丝");
- list.add("粉蒸肉");
- list.add("梅干菜扣肉");
-
- System.out.println("=======迭代器遍历======");
- Iterator ito = list.iterator();
- while (ito.hasNext()) {
- Object o = ito.next();
- System.out.println(o);
- }
-
- //交换前两个元素,正确做法:
- String str1 = (String)list.get(0);
- String str2 = (String)list.get(1);
- list.set(0,str2);
- list.set(1,str1);
-
- //交换前两个元素,错误示例
- //list.set(0,list.get(1));
- //list.set(1,list.get(0));
-
- System.out.println("=======增强for遍历======");
- for (Object ob : list) {
- System.out.println(ob);
- }
- }
错误示例:当调用list.get(1)时,便将list.get(0)覆盖了,此时的 list.get(0)="粉蒸肉"。
当然,面对元素较少的List ,你也可以选择重新赋初值,示例如下:
- list.set(0,"粉蒸肉");
- list.set(1,"鱼香肉丝");
打印结果:
案例二:当list传入的不是字符串,而是一个对象时:
- public static void main(String[] args) {
-
- List list = new LinkedList();
- // List list = new Vector();
- // List list = new ArrayList();
- list.add(new Book("红楼小梦","曹雪芹",35.5));
- list.add(new Book("霸王别姬","张艺谋",98.5));
- list.add(new Book("一代妖姬","未知",30.5));
- list.add(new Book("前任三传","郑恺",32.5));
-
- System.out.println("=======迭代器遍历======");
- Iterator ito = list.iterator();
- while (ito.hasNext()) {
- Object o = ito.next();
- System.out.println(o);
- }
-
- Book book1 = (Book)list.get(0);
- Book book2 = (Book)list.get(1);
- //交换前两个元素
- list.set(0,book2);
- list.set(1,book1);
-
- System.out.println("=======增强for遍历======");
- for (Object ob : list) {
- System.out.println(ob);
- }
- }
此时,是创建的Book对象,而set()方法中并不会,覆盖赋值后的Book对象,只是对Book实例的引用而已。
打印结果:
小结: