数値が2つの異なるオブジェクトの内部にある場合、最小の2つの数値を取得する最良の方法を見つけようとしています。両方のオブジェクトではなく、それぞれがヌルにすることができます。これにより、NULLポインタ例外が発生する可能性があります。各オブジェクトには独自のgetValue()メソッドがあり、これはLong値を返します。私が行うことを希望されないこと/それ以外の場合は基本的にあります:javaは、2つの異なるオブジェクト型から来る2つの数値の中で、最小値を見つけることができます。
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()));
私はこのように感じる非常に簡単な問題であることが、私のすべきです脳はそれが動作するのを許さない。オブジェクトがヌルになる可能性のある状況をバイパスできる最小限の機能が必要ですか?
をしているのですか? –
Long型のものです – user2869231
なぜNullPointerExceptionをキャッチしないのですか? –