Java 核心技术(第八版)卷1:基础知识:例13-2P567LinkedListTest

superfreak 2022-05-14 15:05:25 阅读数:648

java技术核心技术核心第八版
import java.util.*;
//本程序演示了 链表的基础操作
public class LinkedListTest {
public static void main(String[] args)
{
List<String> first_list=new LinkedList<String>();
first_list.add("Amy");
first_list.add("Carl");
first_list.add("Erica");
System.out.println("Original first_list:"+first_list);
ListIterator<String> iter_a=first_list.listIterator();
iter_a.next();//略过第一个元素,
iter_a.add("Juliet");//这样就在Amy之后,添加了Juliet 这个元素
System.out.println("After use iter_a.next() and iter_a.add, a:"+first_list);
// iter_a.set("new new new ");//这样直接使用set会报错
// System.out.println("After use iter_a.set(), a:"+a);
iter_a.next();//首先调用一次 next,再使用set
iter_a.set("IamNew");//set 方法 会取代next 或previous 方法返回的上一个元素。
System.out.println("set method will replace the element 's value after use next or previous:");
System.out.println("After use iter_a.next and iter_a.set(), a:"+first_list);
ListIterator<String> iter_aa=first_list.listIterator();
iter_aa.add("IamNewNew");
System.out.println("first we create a new iterator,then use add,we will add the new element to the head of the list" +
" a:"+first_list);
System.out.println("the previous index is:"+iter_aa.previousIndex());
System.out.println("the next index is"+iter_aa.nextIndex());
System.out.println("***Below is the orginal code of the core java book***");
List<String> a=new LinkedList<String>();
a.add("Amy");
a.add("Carl");
a.add("Erica");
System.out.println("Original a:"+a);
List<String> b=new LinkedList<String>();
b.add("Bob");
b.add("Doug");
b.add("France");
b.add("Gloria");
System.out.println("Original b:"+b);
//merge the words from b to a
ListIterator<String> aIter=a.listIterator();
Iterator<String> bIter=b.iterator();
while (bIter.hasNext())
{
if(aIter.hasNext()) aIter.next();
aIter.add(bIter.next());
}
System.out.println("After merge b to a:"+a);
//remove every second word from b
bIter=b.iterator();
while (bIter.hasNext())
{
bIter.next();//skip one element
if(bIter.hasNext())
{
bIter.next();//skip next element
bIter.remove();//remove that element
}
}
System.out.println(b);
//批量操作:从a 中删除所有b中的word
a.removeAll(b);
System.out.println(a);
}
}

结果如下:

Original first_list:[Amy, Carl, Erica]
After use iter_a.next() and iter_a.add, a:[Amy, Juliet, Carl, Erica]
set method will replace the element 's value after use next or previous:
After use iter_a.next and iter_a.set(), a:[Amy, Juliet, IamNew, Erica]
first we create a new iterator,then use add,we will add the new element to the head of the list a:[IamNewNew, Amy, Juliet, IamNew, Erica]
the previous index is:0
the next index is1
***Below is the orginal code of the core java book***
Original a:[Amy, Carl, Erica]
Original b:[Bob, Doug, France, Gloria]
After merge b to a:[Amy, Bob, Carl, Doug, Erica, France, Gloria]
[Bob, France]
[Amy, Carl, Doug, Erica, Gloria]
进程已结束,退出代码0

版权声明:本文为[superfreak]所创,转载请带上原文链接,感谢。 https://blog.csdn.net/superfreak/article/details/124738825