今天遇到这样一个问题,就是需要去除数组中的重复元素,到网上查了下,用hashset觉得很方便:
- package com.example;
- import java.util.Arrays;
- import java.util.HashSet;
- import java.util.Set;
- /** This class is a Java tutorial for detect and remove duplicate array elements
- */
- public class Test{
- /** This method shows how to check and delete duplicate array elements
- */
- public static void main(String[] args) {
- String[] str = new String[10];
- //Initializing the array with duplicate elements
- for(int i=0;i<10;i++){
- str[i] = "str";
- }
- //remove duplicates here
- Set s = new HashSet(Arrays.asList(str));
- System.out.println(s);
- }
- }
不过这样不一定能保存原来顺序了,如果要保持得用LinkedHashSet,最后toArray()就可以了
本文介绍了一种使用HashSet去除数组中重复元素的方法,并提供了一个Java示例。示例中通过将包含重复元素的数组转换为HashSet集合来实现重复项的删除,同时指出了此方法可能改变原有元素顺序的问题。

被折叠的 条评论
为什么被折叠?



