Sorting an array of strings in Java

前端 未结 3 1759
半阙折子戏
半阙折子戏 2020-12-22 12:59

The user is allowed to play with an array of strings. They can add strings to the array, remove strings from the array, search for strings in the array, and eventually they

3条回答
  •  执念已碎
    2020-12-22 13:40

    I guess the simple way of doing things really would be:

    static String[] strArray;
    static {
        strArray = new String[5];
        for(int i = 0, i < strArray.length; i++)
        {
            strArray[i] = "";
        }
    }
    

    And then just call

    Arrays.sort(strArray);
    

    When you want to sort it. If that doesn't work, although I think it should; your initial approach would have been the following:

        List stringList = new ArrayList();
        for(int i = 0; i < strArray.length; i++)
        {
           stringList.add(strArray[i]);
        }
        Collections.sort(stringList);
        strArray = stringList.toArray(new String[stringList.size()]);
    

    Although it clearly doesn't seem very memory-friendly.

提交回复
热议问题