【问题标题】:java find the smallest of two numbers coming from two different object types when one can be null当一个可以为空时,java找到来自两种不同对象类型的两个数字中的最小者
【发布时间】:2016-08-20 19:23:42
【问题描述】:

当数字是两个不同对象内部的属性时,我试图找出获取两个数字中最小的数字的最佳方法。每个对象(但不是两个)都可以为空,这可能导致空指针异常。每个对象都有自己的 getValue() 方法,该方法将返回一个 Long 值。有一些基本的 if/else 我不想做:

if (obj1 != null && obj2 != null) {  // neither object is null
    minValue = obj1.getValue() <= obj2.getValue() ? obj1.getValue() : obj2.getValue();
} else if (obj1 == null && obj2 != null) { // only obj1 is null
    minValue = obj2.getValue();
} else { // only obj2 is null (they can't both be null, so we don't need an if for the situation where they're both null)
    minValue = obj1.getValue();
}

我尝试了其他一些方法:

// can throw null pointer exception
Collections.min(Arrays.asList(obj1.getValue(), obj2.getValue()));

// while both objects have a getValue() method, they are of different types, so mapping doesn't work
Collections.min(Arrays.asList(obj1, obj2)
    .filter(obj -> obj != null)
    .map(obj -> obj.getValue()) // this line will fail since the methods correspond to different objects
    .collect(Collectors.toList()));

我觉得这应该是一个相当简单的问题,但我的大脑不允许它工作。由于有一些 min 函数,您可以在对象可以为 null 的情况下进行双向处理?

【问题讨论】:

  • value 的类型是什么?
  • 它们的类型是 Long
  • 为什么不直接捕获 NullPointerException?
  • 因为这很丑:/而且,这里先检查空值比捕获空指针更标准
  • mapToLong 可能比 map 更合适,但这仍然会遇到问题,即“getValue()”是一种针对 2 种不同类型对象的方法(它们不是同一个 pojo)

标签: java min


【解决方案1】:
long minValue = Math.min(obj1 == null ? Long.MAX_VALUE : obj1.getValue(),
                         obj2 == null ? Long.MAX_VALUE : obj2.getValue());

【讨论】:

  • 如果x.getValue() == null怎么办?
  • 老鼠!就像我在输入同样的东西一样!
  • @BoristheSpider 根据 OP,它不应该。所以这将抛出一个 NPE 并发出违反先决条件的信号。
【解决方案2】:

我不确定我是否完全理解你的问题,但如果我理解了,这样的事情可能会奏效:

if(obj1 == null) 
   minValue = obj2.getValue();
else if(obj2 == null)
   minValue = obj1.getValue();
else minValue = obj1.getValue() < obj2.getValue() ? obj1.getValue() : obj2.getValue();

【讨论】:

    【解决方案3】:

    您可以有一个方法接受您的 ObjType,执行 null 检查并返回 Long.MAX_VALUE,或者如果它为 null,则返回该值。

    public Long getVal(ObjType val)
    {
        if(val != null)
        {
           return val.getValue();
        }
        return Long.MAX_VALUE;
    }
    

    然后做

    Math.min(obj1, obj2);
    

    【讨论】:

    • 对象类型不同
    猜你喜欢
    • 1970-01-01
    • 2023-01-27
    • 1970-01-01
    • 2018-04-08
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    • 2015-03-04
    • 1970-01-01
    相关资源
    最近更新 更多