提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
列表、链接列表和列表迭代器。
/* 来自 时代Java公众号 - nowjava.com*/ import java.util.LinkedList; import java.util.List; import java.util.ListIterator; public class Main { public static void main(String[] args) { // add colors elements to list1 String[] colors = { "black", "yellow", "green", "blue", "violet", "silver" }; List<String> list1 = new LinkedList<>(); for (String color : colors) list1.add(color); // add colors2 elements to list2 String[] colors2 = { "gold", "white", "brown", "blue", "gray", "silver" }; List<String> list2 = new LinkedList<>(); /*来自 N o w J a v a . c o m*/ for (String color : colors2) list2.add(color); list1.addAll(list2); // concatenate lists list2 = null; // release resources printList(list1); // print list1 elements convertToUppercaseStrings(list1); // convert to uppercase string printList(list1); // print list1 elements System.out.printf("%nDeleting elements 4 to 6..."); removeItems(list1, 4, 7); // remove items 4-6 from list printList(list1); // print list1 elements } // output List contents private static void printList(List<String> list) { System.out.printf("%nlist:%n"); for (String color : list) System.out.printf("%s ", color); System.out.println(); } // locate String objects and convert to uppercase private static void convertToUppercaseStrings(List<String> list) { ListIterator<String> iterator = list.listIterator(); while (iterator.hasNext()) { String color = iterator.next();