問題描述
已知陣列存放一批QQ號碼,QQ號碼最長為11位,最短為5位 String[] strs = {"12345","67891","12347809933","98765432102","67891","12347809933"}
。 將該陣列裡面的所有qq號都存放在LinkedList
中,將list
中重複的元素刪除,將list
中所有元素分別用迭代器
和增強for迴圈
列印出來。
參考思路
1 將陣列中的所有qq號存放在LinkedList
中
import java.util.LinkedList;
import java.util.List;
public class Main {
public static void main(String[] args) {
String[] strings = {"12345","67891","12347809933","98765432102","67891","12347809933"};
List<String> list = new LinkedList<>();
for (String s : strings) {
list.add(s);
}
System.out.println(list);
}
}
把陣列裡的元素新增到一個集合類中,存在一種簡潔的寫法——使用Collections
類中定義的addAll
方法。如果檢視原始碼,會發現它其實也是去使用了foreach
迴圈,因此可以理解上述寫法的縮寫形式。
@SafeVarargs
public static <T> boolean addAll(Collection<? super T> c, T... elements) {
boolean result = false;
for (T element : elements)
result |= c.add(element);
return result;
}
透過addAll
方法上述程式碼可以簡化為:
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// 已知陣列存放了一批qq號
String[] strings = {"12345","67891","12347809933","98765432102","67891","12347809933"};
// 1 將陣列中所有qq號都存放在LinkedList裡面
List<String> list = new LinkedList<>();
Collections.addAll(list, strings);
System.out.println(list);
// => [12345, 67891, 12347809933, 98765432102, 67891, 12347809933]
}
}
PS. 實際編碼時可經常性地輸出中間變數進行除錯,而不是一定要寫完程式碼才執行!
2 將list
中重複的元素刪除
存在多種思路(人工刪除list
中重複元素相對繁瑣),這裡採用一種更簡潔的辦法——透過LinkedHashSet
清除list
中的重複元素
import java.util.*;
public class Main {
public static void main(String[] args) {
String[] strings = {"12345","67891","12347809933","98765432102","67891","12347809933"};
List<String> list = new LinkedList<>();
Collections.addAll(list, strings);
// System.out.println(list);
// => [12345, 67891, 12347809933, 98765432102, 67891, 12347809933]
Set<String> set = new LinkedHashSet<>(list);
list.clear();
list.addAll(set);
System.out.println(list);
// => [12345, 67891, 12347809933, 98765432102, 67891, 12347809933]
}
}
3 分別用迭代器和增強for迴圈列印list中所有元素
import java.util.*;
public class Main {
public static void main(String[] args) {
String[] strings = {"12345","67891","12347809933","98765432102","67891","12347809933"};
List<String> list = new LinkedList<>();
Collections.addAll(list, strings);
// System.out.println(list);
// => [12345, 67891, 12347809933, 98765432102, 67891, 12347809933]
Set<String> set = new LinkedHashSet<>(list);
list.clear();
list.addAll(set);
// System.out.println(list);
// => [12345, 67891, 12347809933, 98765432102]
System.out.println("迭代器:");
Iterator ite = list.iterator();
while (ite.hasNext()) {
System.out.print(ite.next() + " ");
}
System.out.println("\n增強for:");
for (String s : list) {
System.out.print(s + " ");
}
}
}