我的目标是要求用户输入名字和姓氏,然后将其转换为自定义的FullName类,然后搜索HashMap以查找具有相同名字和姓氏的密钥并返回该值。出于某种原因,每当我运行代码并将名称放入时,我都会得到null。
package hw4;
import java.io.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class Test2 {
public static void main(String[] args) throws FileNotFoundException, IOException {
HashMap<FullName, Integer> map = new HashMap<>();
FullName n = new FullName("John", "Smith");
map.put(n, 1);
String f, l;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("First: ");
f = in.readLine();
System.out.print("Last: ");
l = in.readLine();
FullName fl = new FullName(f, l);
System.out.print(map.get(fl));
}
}
这是FullName类。
public class FullName
{
private final String firstName;
private final String lastName;
public FullName(String first, String last) {
firstName = first;
lastName = last;
}
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
public boolean equals(FullName otherName)
{
if (firstName == otherName.firstName && lastName == otherName.lastName)
{return true;}
return false;
}
}
答案 0 :(得分:0)
你还没有真正重写equals方法。因为equals将Object作为参数。另外,使用equals来比较不是==的对象。 ==比较参考变量。
import java.io.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class Test2 {
public static void main(String[] args) throws FileNotFoundException, IOException {
HashMap<FullName, Integer> map = new HashMap<>();
FullName n = new FullName("John", "Smith");
map.put(n, 1);
System.out.println(n.hashCode());
String f, l;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
f = in.readLine();
l = in.readLine();
FullName fl = new FullName(f, l);
System.out.println(fl.hashCode());
System.out.print(map.containsKey(fl));
}
}
class FullName {
private final String firstName;
private final String lastName;
public FullName(String first, String last) {
firstName = first;
lastName = last;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
@Override
public boolean equals(Object obj) {
FullName otherName = (FullName) obj;
if (getFirstName().equals(otherName.getFirstName()) && getLastName().equals(otherName.getLastName())) {
return true;
}
return false;
}
@Override
public int hashCode() {
return firstName.length()+lastName.length();
}
}