これは私が二番目に高い数値を取得しに行くかの方法である:
// The array containing number.
int[] number = {1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10};
// The int[] is copied to Integer[] array. This is done because the Arrays class cannot sort primitives (such as int). If any other primitive type, they can be converted to their respective objects.
Integer[] numberInteger = new Integer[number.length];
// Populate the Integer[] with data from int[].
for(int i = 0; i<number.length; i++)
{
numberInteger[i] = number[i];
}
// Sort the Integer[] array in reverse order.
Arrays.sort(numberInteger, Collections.<Integer>reverseOrder());
// Print the result out.
System.out.println("The second highest number is: "+numberInteger[1]);
// Output is~~~~~~~ The second highest number is: 9
あなたが他のプリミティブ型(例えば、[] double)を持っている場合、それはそれのそれぞれのオブジェクト(例えばダブル[]にコピーすることができます)。
P.S. Java 8を使用している場合は、Integer []配列を簡単に取り込むことができます。 Streamsを使用してInteger []を生成できます。
// Instead of using a for loop, Streams are used.
Integer[] numberInteger = Arrays.stream(number).boxed().toArray(Integer[]::new);
実際には、 'Arrays.sort(myArray); return myArray [myArray.length - 2]; ' –
2つの余分な一時変数は正常です... – Kelvin
私はちょうど2つの変数を使用すると思います – Fourierstudent