2016-04-26 6 views
-1

数値が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())); 

私はこのように感じる非常に簡単な問題であることが、私のすべきです脳はそれが動作するのを許さない。オブジェクトがヌルになる可能性のある状況をバイパスできる最小限の機能が必要ですか?

+1

をしているのですか? –

+0

Long型のものです – user2869231

+0

なぜNullPointerExceptionをキャッチしないのですか? –

答えて

2
long minValue = Math.min(obj1 == null ? Long.MAX_VALUE : obj1.getValue(), 
         obj2 == null ? Long.MAX_VALUE : obj2.getValue()); 
+0

'x .getValue()== null'? –

+0

ラット!同じことを入力していたのと同じように! –

+1

@BoristheSpiderそれは、OPによるとすべきではありません。そうすれば、NPEが投げられ、前提条件の違反が通知されます。 –

0

私は、私は完全にあなたの質問を理解していないが、私がしなければ、このような何かが仕事ができる:

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

あなたのOBJTYPEに取るメソッドを持つことができ、ヌルチェックを行いますLong.MAX_VALUEを返します。値がnullの場合は値を返します。

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

は、[値]のタイプ(複数可)何

Math.min(obj1, obj2); 
+0

オブジェクトは同じタイプではありません – mariusz2108

関連する問題