【问题标题】:Not able to sort integer list in ascending order无法按升序对整数列表进行排序
【发布时间】:2017-03-16 13:02:19
【问题描述】:

我有来自 json 文件的整数列表,并打印该完整列表。对该列表进行排序后,它以不同的方式打印

    List<Integer> list = new ArrayList<Integer>(keys);
    System.out.println("list is :" + list);
    Collections.sort(list);
    System.out.println("after sorting is:"+list);

o/p 列表:

[338, 339, 332, 333, 159, 330, 158, 331, 157, 336, 156, 337, 155,etc...0,1,14]

而不是在0,1,2 等中排序......它按以下方式排序:

排序后是:

[0, 1, 10, 100, 101, 102, 103, 104, 105,etc..]

代码:

response = httpUtil.getResponse(aperture_url);
parser = new JSONParser();
object = parser.parse(((String) response));
jsonObject = (JSONObject) object;
aperture_details = (JSONObject) jsonObject.get("response");
historic_price = (JSONObject) aperture_details.get("historic_price");
System.out.println("historic_price:" + historic_price);
keys = historic_price.keySet();
List<Integer> list = new ArrayList<Integer>(keys);
System.out.println("list is :" + list);
Collections.sort(list);
System.out.println("after sorting is:"+list);

【问题讨论】:

  • 原来的列表里有2吗?
  • 不是0、1、10、100、101、102、103、104、105 ....升序吗?
  • 为了澄清 OP 的观点,我相信他们的意思是它的排序更像 List&lt;String&gt; 可能排序。 0,1,10,11,2,21,22,3
  • 请提供minimal reproducible example - 如果不亲自复制,我很难相信这里的行为。
  • 我无法重现您的错误,至少当列表元素确实是 Integers 时,如列表的类型参数所示。如果您提供 minimal reproducible example 来演示问题,那么我怀疑我们将能够告诉您您的元素 不是,实际上是 Integers,而是 Strings,并且您已关闭或忽略编译器的类型安全警告。

标签: java


【解决方案1】:

请提供您对变量keys的定义!!

你说你是从 JSON 文件中获取它的,所以我想你使用类似 JSON.parse(...content of your file here...) 的东西

如果是这样,键应该是一个数组。

通过更改尝试一下
List&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;(keys);

List&lt;Integer&gt; list = new ArrayList&lt;Integer&gt;(Arrays.asList(keys));

【讨论】:

  • Set keys = new HashSet(); -- 这是钥匙
  • 我收到上述错误:构造函数 ArrayList(List>) 未定义
  • 您收到此错误,因为我猜测 keys 是一个数组是错误的。将keys 用作Set&lt;Integer&gt;,尝试使用keys.toString() 而不是Arrays.asList(keys))。重要提示:为此,您使用 new ArraList&lt;&gt;new ArraList&lt;Object&gt; 而不是 new ArrayList&lt;Integer&gt;
  • 你能举个例子吗?
  • 但它不是List&lt;Set&lt;T&gt;&gt;new ArrayList&lt;T&gt;(Collection&lt;T&gt; c) 只是将容器的元素复制到列表中,而不是将整个集合添加为元素AFAIK
猜你喜欢
  • 2013-10-16
  • 2012-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-23
  • 2020-10-05
  • 1970-01-01
相关资源
最近更新 更多