Java: sort a String array, whose strings represent int

后端 未结 8 1171
北恋
北恋 2020-12-16 14:09

I have String[] array like

{\"3\",\"2\",\"4\",\"10\",\"11\",\"6\",\"5\",\"8\",\"9\",\"7\"}

I want to sort it in numerical ord

8条回答
  •  半阙折子戏
    2020-12-16 14:49

    I think by far the easiest and most efficient way it to convert the Strings to ints:

    int[] myIntArray = new int[myarray.length];
    
    for (int i = 0; i < myarray.length; i++) {
        myIntArray[i] = Integer.parseInt(myarray[i]);
    }
    

    And then sort the integer array. If you really need to, you can always convert back afterwards:

    for (int i = 0; i < myIntArray.length; i++) {
        myarray[i] = "" + myIntArray[i];
    }
    

    An alternative method would be to use the Comparator interface to dictate exactly how elements are compared, but that would probably amount to converting each String value to an int anyway - making the above approach much more efficient.

提交回复
热议问题