数组去重复,题目: 原始数组是{4,2,4,6,1,2,4,7,8},得到结果{4,2,6,1,7,8}
对数组操作如果想得到新数组,面临的问题是
1,新数组的长度是不一定的,即要指定一个可变长度的数组。
2,如何从旧数组中删除元素(或者说往新数组里增加元素)。
这两点数组都是不具备的,那么有此特性的就是集合了。
【HashSet也可以去重,但是HashSet会将数据随机输出,会打乱原有的顺序。如果不打乱原有顺序,就要覆写hashCode、equals方法。】
分别用remove、add方法实现
说一下这里方法的思想(有点像选择排序):拿第1个与第2个、第3个、第4个、第5个、、、、、、比较,如果重复,就从list里去掉,得到新的list
再拿新的list的第2个与第3个、第4个、第5个、、、、、、比较,如果重复,就从list里去掉,得到新的list。
、、、、、、
就得到了不重复的数组了。
public static void main(String[] args) {
List<Integer> all = new ArrayList<>();
int[] num = { 4, 2, 4, 6, 1, 2, 4, 7, 8 };
for (int i = 0; i < num.length; i++) {
all.add(num[i]);
}
for (int i = 0; i < all.size(); i++) {
int x = all.get(i);
for (int j = 1 + i; j < all.size(); j++) {
if (x == all.get(j)) {
all.remove(j);
}
}
}
System.out.println(all);
}
还有个比较简洁的方法,利用list的 boolean contains ()方法
public static void main(String[] args) {
int[] arr = { 4, 2, 4, 6, 1, 2, 4, 7, 8 };
//创建对象
//这里没有泛型,若果有泛型则报错
List data = new ArrayList();
//增强for
for (int num : arr) {
if (!data.contains(num)) {
data.add(num);
}
}
//打印数组
System.out.println(data);
}
由以上案例,总结了数组去除元素的方法。
去重最好是用往新集合里add元素的方法。remove的话,比较麻烦,容易出错,因为每次remove总是删除第一次出现的,并且remove后,集合的长度就变了,再遍历的话就容易出错。
如果用remove:
1、遍历原数组,用一个新数组记录指定元素出现的角标,
2、遍历角标得到值,在集合中删除。
用add方法,代码如下:
public class RemoveArrayElement {
public static void main(String[] args) {
int[] arr = { 1, 3, 4, 5, 0, 0, 6, 6, 0, 5, 4, 7, 6, 7, 0, 5 };
removeRepeatValue(arr);
removeValue(arr, 0);
}
/**
* 去除数组中重复元素
*
* @param arr
* 要操作的数组
*/
public static void removeRepeatValue(int[] arr) {
List list = new ArrayList();
for (int i = 0; i < arr.length; i++) {
if (list.contains(arr[i]))
continue; // 新的集合中已有此元素,则不存储
list.add(arr[i]);
}
System.out.println("数组去重:" + list + "新数组长度:" + list.size());
}
/**
* 去除数组中的指定元素
*
* @param arr
* 要操作的数组
* @param value
* 要去除的元素
*/
public static void removeValue(int[] arr, int value) {
List list = new ArrayList();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == value)
continue; // 如果是要去除的元素,则不存储
list.add(arr[i]);
}
System.out.println("去除数组中的" + value + ":" + list + "新数组长度:"
+ list.size());
}
}