Arraylist 去重
时间: 2023-09-12 10:03:24 浏览: 88
可以使用HashSet来去重,将ArrayList转换为HashSet,再将HashSet转换回ArrayList即可。
示例代码:
```java
ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("orange");
list.add("apple");
HashSet<String> set = new HashSet<>(list);
list.clear();
list.addAll(set);
System.out.println(list); // 输出 [orange, banana, apple]
```
在这个例子中,通过将ArrayList转换为HashSet,重复的元素被自动去除,最后再将HashSet转换回ArrayList。
相关问题
ArrayList去重
可以使用 HashSet 来去重,具体实现方法如下:
```java
ArrayList<Integer> list = new ArrayList<Integer>();
// 添加元素到 list 中
HashSet<Integer> set = new HashSet<Integer>(list);
list.clear();
list.addAll(set);
```
以上代码将 ArrayList 中的重复元素去重。
ArrayList 去重
可以通过 HashSet 来进行 ArrayList 的去重操作。具体步骤如下:
1. 创建一个 HashSet 对象,并将 ArrayList 中的元素逐个添加到 HashSet 中。
2. 创建一个新的 ArrayList 对象,将 HashSet 中的元素逐个添加到新的 ArrayList 中。
下面是 Java 代码示例:
```java
import java.util.ArrayList;
import java.util.HashSet;
public class ArrayListRemoveDuplicate {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(2);
list.add(4);
list.add(5);
list.add(1);
HashSet<Integer> set = new HashSet<>(list);
ArrayList<Integer> newList = new ArrayList<>(set);
System.out.println("原始 ArrayList: " + list);
System.out.println("去重后的 ArrayList: " + newList);
}
}
```
输出结果为:
```
原始 ArrayList: [1, 2, 3, 2, 4, 5, 1]
去重后的 ArrayList: [1, 2, 3, 4, 5]
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)