java - 调用 hashmap.get(object) 时在 HashMap 对象中获取 null 值

标签 java null hashmap

我已经实现了 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/

相关文章:

java - Java HashMap 列表

groovy - 在groovy中初始化 map 内的 map

java - 需要解释,为什么向 Singleton 类添加 implements Serializable 是不够的?

java - Spring boot - Snowflake JDBC - 应用程序加载时自动更改 session

kotlin - Kotlin 空安全是否在编译器中实现?

arrays - Kotlin - 对象数组(无 null)

java - 查找 HashMap 是否包含值并仅删除该值

java - Android 示例屏幕及其源 xml 代码

java - 如何使 Websphere App 将每个应用程序日志条目重定向到不同的文件?

java - 返回java字符串而不是返回null