题目1:编写一个应用程序,在主类Test1类中,创建两个链表List对象,分别存储通过键盘输入的字符串内容
——“chen”,“wang”,“liu”,“zhang”和“chen”,“hu”,“zhang”
(假定输入的内容在各自的链表中没有重复的),输出显示这两个链表List对象并集的结果。
import java.util.*; public class Test1 { public static void main(String args[]) { getList(); } private static void getList() { LinkedList<String> List1 = new LinkedList<String>(); LinkedList<String> List2 = new LinkedList<String>(); List<String> unionList = new ArrayList<String>(); try { Scanner reader = new Scanner(System.in); System.out.println("please input list1: "); String a = reader.nextLine(); String b = reader.nextLine(); String c = reader.nextLine(); String d = reader.nextLine(); List1.add(a); List1.add(b); List1.add(c); List1.add(d); System.out.println("please input list2: "); String q = reader.nextLine(); String w = reader.nextLine(); String e = reader.nextLine(); List2.add(q); List2.add(w); List2.add(e); // 获取去重并集 unionList = receiveUnionList(List1, List2); Iterator<String> unionIterator = unionList.iterator(); System.out.println("Union: "); while (unionIterator.hasNext()) { System.out.println(unionIterator.next()); } } catch (Exception e) { e.printStackTrace(); } } public static List<String> receiveUnionList(List<String> List1, List<String> List2) { List<String> resultList = new ArrayList<String>(); Set<String> firstSet = new TreeSet<String>(List1); for (String id : List2) { firstSet.add(id); } resultList = new ArrayList<String>(firstSet); return resultList; } }
运行结果: