去除 Java 数组中重复元素的方法是:将数组转换为集合;创建一个不允许重复元素的新集合;将数组元素添加到新集合中;将新集合转换为数组。
如何去除 Java 数组中的重复元素
在 Java 中,去除数组中重复元素的常用方法是使用集合。集合是一种数据结构,它不允许重复元素。
方法:
Arrays.asList() 方法将数组转换为 List。HashSet 或 TreeSet 等集合,该集合不允许重复元素。List 元素添加至新集合:使用 addAll() 方法将 List 元素添加到新集合中。toArray() 方法将新集合转换为数组。示例:
int[] arr = {1, 2, 3, 4, 1, 2};
// 将数组转换为 List
List list = Arrays.asList(arr);
// 创建 HashSet
Set set = new HashSet<>();
// 将 List 元素添加到 HashSet
set.addAll(list);
// 将 HashSet 转换为数组
int[] newArr = new int[set.size()];
int i = 0;
for (Integer num : set) {
newArr[i++] = num;
} 输出:
[1, 2, 3, 4]
注意:
HashSet 不维护插入顺序,因此新数组中的元素顺序可能与原始数组不同。TreeSet 会按自然顺序或自定义比较器(如果提供的话)维护元素顺序。