1.将数组中所有字符串存进LinkedList中,将list中重复元素删除。2.定义两个遍历数组方法遍历Collection,将Collection中的所有元素分别用迭代器打印出来
时间: 2023-06-06 13:04:58 浏览: 94
好的,我可以帮助你解决这个问题。以下是代码示例:
1.
```
String[] arr = {"a", "b", "c", "d", "a", "e"};
LinkedList<String> list = new LinkedList<>(Arrays.asList(arr));
Set<String> set = new HashSet<>(list);
list.clear();
list.addAll(set);
```
2.
```
public void traverseCollection(Collection<?> collection){
for(Object obj : collection){
System.out.println(obj.toString());
}
}
public void traverseCollectionWithIterator(Collection<?> collection){
Iterator<?> iterator = collection.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next().toString());
}
}
```
你可以根据需要对代码进行适当修改。希望能帮到你。
相关问题
分别使用java编写Collection、list、arraylist、vector、linkedlist实现存储字符串并遍历
1. Collection接口的实现:
```java
import java.util.*;
public class CollectionDemo {
public static void main(String[] args) {
Collection<String> collection = new ArrayList<>();
collection.add("apple");
collection.add("banana");
collection.add("cherry");
for (String s : collection) {
System.out.println(s);
}
}
}
```
2. List接口的实现:
```java
import java.util.*;
public class ListDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");
for (String s : list) {
System.out.println(s);
}
}
}
```
3. ArrayList的实现:
```java
import java.util.*;
public class ArrayListDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");
for (String s : list) {
System.out.println(s);
}
}
}
```
4. Vector的实现:
```java
import java.util.*;
public class VectorDemo {
public static void main(String[] args) {
List<String> list = new Vector<>();
list.add("apple");
list.add("banana");
list.add("cherry");
for (String s : list) {
System.out.println(s);
}
}
}
```
5. LinkedList的实现:
```java
import java.util.*;
public class LinkedListDemo {
public static void main(String[] args) {
List<String> list = new LinkedList<>();
list.add("apple");
list.add("banana");
list.add("cherry");
for (String s : list) {
System.out.println(s);
}
}
}
```
阅读全文