使用java中的Collections.reverse()方法反转数组未按预期功能运行

huangapple go评论96阅读模式
英文:

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&lt;int&gt; is not (yet) legal java.

Thus, that makes a List&lt;int[]&gt; (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.

huangapple
  • 本文由 发表于 2020年10月28日 08:37:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/64564856.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定