私はmin maxというオブジェクトに配列の最小値と最大値を返すコードをいくつか持っています。私の質問はforループの中にあり、各反復で新しいMinMaxオブジェクトを作成する必要があります。それとも私たちはとても似のMinMaxのメンバ変数を更新することができます:メンバ変数へのアクセスと新しいオブジェクトの作成
globalMinMax.largest = Math.min(globalMinMax.smallest, localMinMax.smallest);
globalMinMax.smallest = Math.max(globalMinMax.largest, localMinMax.largest));
をする代わりに、我々は
private static class MinMax {
public Integer smallest;
public Integer largest;
public MinMax(Integer smallest, Integer largest) {
this.smallest = smallest;
this.largest = largest;
}
private static MinMax minMax(Integer a, Integer b) {
return Integer.compare(b, a) < 0 ? new MinMax(b, a) : new MinMax(a, b);
}
}
public static MinMax findMinMax(List<Integer> A) {
if (A.size() <= 1) {
return new MinMax(A.get(0), A.get(0));
}
MinMax globalMinMax = MinMax.minMax(A.get(0), A.get(1));
// Process two elements at a time.
for (int i = 2; i + 1 < A.size(); i += 2) {
MinMax localMinMax = MinMax.minMax(A.get(i), A.get(i + 1));
**********Do we need to create a new object here?*****
globalMinMax
= new MinMax(Math.min(globalMinMax.smallest, localMinMax.smallest),
Math.max(globalMinMax.largest, localMinMax.largest));
}
// If there is odd number of elements in the array, we still
// need to compare the last element with the existing answer.
if ((A.size() % 2) != 0) {
globalMinMax
= new MinMax(Math.min(globalMinMax.smallest, A.get(A.size() - 1)),
Math.max(globalMinMax.largest, A.get(A.size() - 1)));
}
return globalMinMax;
}
なぜ 'Integer.compare(b、a)<0'は' b shmosel
問題があると思われますか?どうしてそう思うの?あなたのアイデアを試しましたか?なぜ入力が必要なのですか? – shmosel
Imは、オブジェクトに直接アクセスするのではなく、新しいキーワードを使用することに利点があるかどうか疑問に思っています。著者がその決定を下した理由とそれが重要かどうか疑問に思っています – Matt