gpt4 book ai didi

java - Java中删除重复的对象

转载 作者:行者123 更新时间:2023-12-01 06:36:07 24 4
gpt4 key购买 nike

我的用户对象如下所示:

用户.java:

    public class User {
public String firstName;
public String lastName;

public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}

@Override
public int hashCode() {
return (this.firstName.hashCode() + this.lastName.hashCode());
}

@Override
public boolean equals(Object obj) {
if(obj instanceof User) {
User temp = (User) obj;
if(this.firstName.equals(temp.firstName) && this.lastName.equals(temp.lastName)) {
return true;
}
}
return false;
}
}

主程序如下所示:

    import java.util.*; 

class pp {
public static void main(String[] args) {
List<User[]> a = new ArrayList<User[]>();
User[] u = new User[3];

u[0] = new User();
u[0].setFirstName("Mike"); u[0].setLastName("Jordon");

u[1] = new User();
u[1].setFirstName("Jack"); u[1].setLastName("Nicolson");

u[2] = new User();
u[2].setFirstName("Jack"); u[2].setLastName("Nicolson");

a.add(u);

Set<User[]> s = new HashSet<User[]>(a);

for (User[] ss : s) {
for (int i=0; i<ss.length; i++) {
System.out.println(ss[i].getFirstName() + " " + ss[i].getLastName());
}
}
}
}

我期望输出为

Mike Jordon
Jack Nicolson

但不知何故,它保留重复的对象并打印为:

Mike Jordon
Jack Nicolson
Jack Nicolson

谁能告诉我我错过了什么?

谢谢!

最佳答案

你的 equals 方法应该是这样的:

  @Override
public boolean equals(Object obj) {
if(obj instanceof User) {
User temp = (User) obj;
if(this.firstName.equals(temp.firstName) && this.lastName.equals(temp.lastName)) {
return true;
}
}
return false;
}

关于java - Java中删除重复的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11607378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com