【问题标题】:EJB HashMap How to implement a method that compares two objectsEJB HashMap 如何实现比较两个对象的方法
【发布时间】:2015-12-23 09:13:53
【问题描述】:

这是一个 EJB 项目。我需要实现一个比较两个或多个对象的函数,并且一旦单击“添加”或“删除”按钮,我就只能添加或删除一个对象。因此,我的想法是将对象存储在HashMap中,然后进行比较,取其最佳。但是当我运行我的方法时,HashMap 为空。方法不能在其中添加对象。怎样才能使HashMap被操作。我的代码附在下面。

@Stateful
public class ComparePropertySessionBean implements ComparePropertySessionBeanRemote{

public HashMap<Integer, Double> map = new HashMap<Integer, Double>();

@Override
public int getBestPerRoom() {
    Iterator<Integer> iterator = map.keySet().iterator();
    int i = 0;
    double ave = 10000000000.00;
    if (iterator.hasNext()) {
        Integer key = iterator.next();
        if (map.get(key) <  ave) {
            i = key;
            ave = map.get(key);
        }
    }

    return i;
}

@Override
public void addCompareProperty(int propertyId, double price, int noofbedrooms) {

    if (!map.containsKey(propertyId)) {
        map.put(propertyId, price/noofbedrooms);

    }

}

@Override
public void removeCompareProperty(int propertyId) {
    if (map.containsKey(propertyId)) {
        map.remove(propertyId);
    }
}

}

【问题讨论】:

  • 您是说 HashMap 引用为空吗?如果是这样,程序应该崩溃。发布错误消息

标签: java hashmap ejb stateful


【解决方案1】:

map 本身只有在这个类之外的一些其他代码将其设置为 null 时才能在此处为 null。 (这不太可能,但原则上你真的应该将map 字段设为private)。

看到堆栈跟踪会很好,但我看到的大问题是getBestPerRoom() 中的逻辑错误: 如果地图至少有一个条目,则此方法有效,但如果它为空,它将返回 0。如果您的代码随后尝试将此作为 propertyId 调用其他方法,它们将获得一个空条目并且(如果它们是'不仔细检查)将获得 NPE。
为了避免此类问题,您需要妥善处理没有条目的情况。

更一般地说,有更好的方法来构建此代码 - OO 原则建议您应该使用 Property 类来封装有关不同属性的所有信息。然后,您可以通过编写Comparator(或将它们存储在 TreeSet 中)按价格对它们进行排序。
如果您正在编写 EJB 应用程序,这还允许您使用 JPA 轻松地将 Properties 存储在数据库中。

【讨论】:

    猜你喜欢
    • 2016-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-10
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    相关资源
    最近更新 更多