Java数组去重的方法有多种,以下是常见的几种方法:
int[] array = {1, 2, 3, 4, 3, 2, 1};
Set<Integer> set = new HashSet<>();
for (int num : array) {
set.add(num);
}
int[] result = new int[set.size()];
int index = 0;
for (int num : set) {
result[index++] = num;
}
int[] array = {1, 2, 3, 4, 3, 2, 1};
List<Integer> list = new ArrayList<>();
for (int num : array) {
if (!list.contains(num)) {
list.add(num);
}
}
int[] result = list.stream().mapToInt(Integer::intValue).toArray();
int[] array = {1, 2, 3, 4, 3, 2, 1};
int length = array.length;
for (int i = 0; i < length; i++) {
for (int j = i + 1; j < length; j++) {
if (array[i] == array[j]) {
array[j] = array[length - 1];
length--;
j--;
}
}
}
int[] result = Arrays.copyOf(array, length);
以上是三种常见的数组去重方法,根据实际情况选择适合的方法即可。