我已经实现了 HashMap 来存储酒店预订条目。但是我在 .get(object) 方法上得到空值,即使它包含所有键并正确返回键。我已经重写了两个 equals() 和 hashCode() 方法不同的类(bookingSeason 和 Entry),因为 bookingSeason 类也在其他一些类中使用并且它可以正常工作,但在入门类中它不起作用。
public class Entry {
String code;
List<BookingSeason> booking=new ArrayList<>();
public Entry(String code) {
this.code=code;
}
@Override
public boolean equals(Object o) {
if(o==null)
return false;
if(!(o instanceof Entry))
return false;
Entry room=(Entry) o;
return this.code.equals(room.code)&&
this.booking.equals(room.booking);
}
@Override
public int hashCode() {
return Objects.hash(code,booking);
}
}
public class BookingSeason {
LocalDate startDate;
LocalDate endDate;
public BookingSeason(LocalDate startDate,LocalDate endDate) {
this.startDate=startDate;
this.endDate=endDate;
}
@Override
public boolean equals(Object object)
{
if(object==this)
return true;
if(!(object instanceof BookingSeason))
return false;
BookingSeason bS=(BookingSeason) object;
return Objects.equals(startDate,bS.startDate)&& Objects.equals(
endDate,bS.endDate);
}
@Override
public int hashCode() {
return Objects.hash(startDate,endDate);
}
}
public class Hotel {
List<BookingSeason> bookPeriod=new ArrayList<>();
HashMap<Long,Entry> roomEntry =new HashMap<>();
long num;
Entry newRoom=new Entry();
for(int i=101;i<=199;i++) {
num=i;
newRoom.code="A";
newRoom.code=newRoom.code.concat(String.valueOf(i));
roomEntry.put(num,new Entry(newRoom.code));
System.out.println(roomEntry.get(i));
}
}
最佳答案
roomEntry.put(num,new Entry(newRoom.code));
使用长值num
将新的Entry
对象输入到 HashMap 中。
System.out.println(roomEntry.get(i));
使用 int 值 i
尝试获取 Entry
对象。
但是,自从
Long.valueOf(11).equals(Integer.valueOf(11)) == false
它将找不到该条目。您需要将 long/Long 值传递给 get 方法。因此,要么使用
System.out.println(roomEntry.get(num));
或使用
System.out.println(roomEntry.get((long) i));
将解决您的问题。
供引用,另请参阅What are the reasons why Map.get(Object key) is not (fully) generic
关于java - 调用 hashmap.get(object) 时在 HashMap 对象中获取 null 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39802751/