Converting an int array to a String array

前端 未结 14 1429
予麋鹿
予麋鹿 2020-12-01 14:21

So I have this \"list\" of ints. It could be a Vector, int[], List, whatever.

My goal though is to sort the

14条回答
  •  长情又很酷
    2020-12-01 14:51

    Can I use a while loop instead?

    @Test
    public void test() {
        int[] nums = {5,1,2,11,3};
    
        Arrays.sort(nums);
    
        String[] stringNums = new String[nums.length];
        int i = 0;
        while (i < nums.length) {
            stringNums[i] = String.valueOf(nums[i++]);
        }
    
        Assert.assertArrayEquals(new String[]{"1","2","3","5","11"}, stringNums);
    }
    

    Using JUnit assertions.

    Sorry, I'm being flippant. But saying you can't use a for loop is daft - you've got to iterate over the list somehow. If you're going to call a library method to sort it for you (cf Collections.sort()) - that will be looping somehow over the elements.

提交回复
热议问题