' P '

whatever I will forget

Java int arrayの逆sort (Arrays.sort(), Collections.sort())

これね。
int arrayの逆sortよく忘れる。
まあ最悪忘れたらsortしたarrayを逆ループさせてもう一回作り直せばいいだけだけど。

やり方

Collections.reverseOrder()をsortの第二引数にする。第一引数はIntegerのarray。

パターン

  • primitive type/obj type の array - Arrays.sort()
  • list type - Collections.sort()
import java.util.Collections;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Scanner;

public class SortTest{
  public static void main(String[] args) {
    Integer[] array1 = {1,4,6,3,6,7};
    Arrays.sort(array1, Collections.reverseOrder());
    System.out.println(Arrays.toString(array1));

    int[] array2 = {1,4,6,3,6,7};
    ArrayList<Integer> arrayList = new ArrayList<>();
    for(Integer i: array2) {
        arrayList.add(i);
    }
    //Arrays.sort(arrayList, Collections.reverseOrder()); //error: no suitable method found for sort(ArrayList<Integer>,Comparator<Object>)
    Collections.sort(arrayList, Collections.reverseOrder());
    System.out.println(Arrays.toString(arrayList.toArray()));

    Scanner sc = new Scanner(System.in);
    Integer[] test = new Integer[10];
    Arrays.fill(test, 0);

    for(int i=0; i<10; i++) {
        int in = sc.nextInt();
        test[in-1]++;
    }
    Arrays.sort(test, Collections.reverseOrder());
    System.out.println(Arrays.toString(test));
  }
}

参考

beginnersbook.com

追記 5/21

相当困った。まずCollectionsのsortなのかArraysのsortなのかって部分。
ArrayListArray.sort()とかしちゃって大混乱だった。

あとBucker Sort的なのでsortしようとして、
Integer array作ったんだけどnullポがでました。
今更なんですけどIntegerはobjなのでどこも参照していない場合にarray[0]++とかarray[0] += 1とかできまへん。
まずArrays.fill(array,0)してからインクリメントしようね。

さらに追記5/22

primitive typeのarrayはArrays.sort(array, Collections.reverseOrder());は使えません。
char arrayで同じ間違いに遭遇。
error: no suitable method found for sort(char[],Comparator<Object>) が出る。
下記にもある通り、primitive typeのarrayをdescending orderにしたい場合は、Arrays.sort()してから、手動でfor文とかでarrayに作り直すしかない

Arrays.sort() cannot be used directly to sort primitive arrays in descending order.
If you try to call the Arrays.sort() method by passing reverse Comparator defined by Collections.reverseOrder() , it will throw the error

no suitable method found for sort(int[],comparator)

That will work fine with 'Array of Objects' such as Integer array but will not work with a primitive array such as int array.

The only way to sort a primitive array in descending order is, first sort the array in ascending order and then reverse the array in place. This is also true for two-dimensional primitive arrays.

stackoverflow.com