英文:
Reverse an Array using Collections.reverse() method in java not functioning as expected
问题
我试图使用 Java 中的 Collections.reverse()
方法来反转字符数组中的元素。但它没有将它们反转,所以我尝试了一个整数数组,就像我参考的示例中使用的那样,但也没有成功。
这是我的代码:
int[] intarr = {1, 2, 3, 5, 7, 8};
System.out.println(Arrays.toString(intarr));
Collections.reverse(Arrays.asList(intarr));
System.out.println(Arrays.toString(intarr));
它返回两个与输入相同的列表!这里出了什么问题?
英文:
I was trying to reverse elements in a character array using the Collections.reverse() method in java. It wasn't reversing them so i took an integer array as was used in the example i was referring to with no success
Here is my code
int[] intarr = {1,2,3,5,7,8};
System.out.println(Arrays.toString(intarr));
Collections.reverse(Arrays.asList(intarr));
System.out.println(Arrays.toString(intarr));
It returns two lists same as the input! what's going wrong here?
答案1
得分: 5
Arrays.asList(intarr)
并不会产生你认为的效果。
鉴于intarr
是一个基本类型数组,无法简单地将其转换为列表;毕竟,List<int>
在Java中(目前)是不合法的。
因此,这将生成一个List<int[]>
(即,一个int数组的列表),列表中恰好有1个元素:你的int数组。颠倒一个大小为1的列表不会有任何效果,正如你可能猜测的那样。
在不使用第三方库的情况下,对于这个问题没有一种一行代码就能解决的方法。
英文:
Arrays.asList(intarr)
doesn't do what you think it does.
Given that intarr
is a primitive array, it is not possible to simply turn this into a list; after all, a List<int>
is not (yet) legal java.
Thus, that makes a List<int[]>
(as in, a list of int arrays), with exactly 1 element in it: Your int array. Reversing a 1-size list doesn't do anything as you might surmise.
There is no one-liner answer to this short of using third party libraries.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论