一般而言,数组最简单快捷的方法是直接利用HashSet的不重复的特性就可以做到,或者是遍历时利用List的contains 判断是否存在就可以去重了
如果是对象数组,对象的类需要 重写 equal 和 hashCode方法.。
但是面试题经常有数组去重的试题,如果在不使用hashSet 和 list的contains方法情况下,纯数组怎么去重?
可以这么做:
使用一个标识数组来标识重复的元素位置,再新建一个新的数组来存储去重后的元素
User user1 = new User("zjamgs",16,12); //User 需要重写equal 和 hashcode 方法 User user2 = new User("lisi",13,18); User user3 = new User("wangwi",15,13); User user4 = new User("zhangsli",23,10); User user5 = new User("zjamgs",16,12); User user6 = new User("zjamgs1",16,12); User user7 = new User("lisi2",13,18); User user8 = new User("zjamgs",16,12); User user9 = new User("wangwi",15,13); User user10 = new User("zjamgs5",16,12); User[] users = {user1,user2,user3,user4,user5,user6,user7,user8,user9,user10}; int[] userindex = new int[users.length];//标记相同的元素的,0表示未重复,1表示已重复 int repeatCount = 0; for(int i=0;i<users.length;i++){ if(userindex[i]==1)continue; //非常重要 for(int j=users.length-1;j>i;j--){ if(users[i].equals(users[j])){ userindex[j] = 1; repeatCount++; } } } System.out.println(Arrays.toString(userindex); User[] newUsers = new User[users.length - repeatCount]; for (int i = 0;i < userindex.length;i++){ if (userindex[i] == 0){ for (int j = 0;j < newUsers.length;j++){ if(newUsers[j] == null){ newUsers[j] = users[i]; break; } } } } System.out.println(Arrays.toString(newUsers));
User类:
class User implements Comparable<User>{ private String name; private int age; private int index; @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof User)) return false; User user = (User) o; return getAge() == user.getAge() && getIndex() == user.getIndex() && Objects.equals(getName(), user.getName()); } @Override public int hashCode() { return Objects.hash(getName(), getAge(), getIndex()); } @Override public String toString() { return "User [name=" + name + ", age=" + age + ", index=" + index + "]"; } public User(String name, int age, int index) { super(); this.name = name; this.age = age; this.index = index; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public User() { super(); } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int compareTo(User o) { if(this.getAge()<o.getAge()){ return -1; }else if(this.getAge()>o.getAge()){ return 1; } return 0; } }
输出结果:
[0, 0, 0, 0, 1, 0, 0, 1, 1, 0]
[User [name=zjamgs, age=16, index=12],
User [name=lisi, age=13, index=18],
User [name=wangwi, age=15, index=13],
User [name=zhangsli, age=23, index=10],
User [name=zjamgs1, age=16, index=12],
User [name=lisi2, age=13, index=18],
User [name=zjamgs5, age=16, index=12]]
有三个元素是前面已经有的元素,是重复元素,余下的7个都不是重复元素,结果正确
原文地址:https://www.cnblogs.com/hcklqy/p/11610837.html
时间: 2024-10-16 03:00:24