【问题标题】:What is the sorting order when a collection contains character,integer and string in javajava中集合包含字符,整数和字符串时的排序顺序是什么
【发布时间】:2021-09-30 06:41:23
【问题描述】:

当集合中包含字符、整数和字符串时,我对排序首选项有疑问。当它有这种数据时,排序顺序是如何工作的。例如:['a',2,3,5,'b',ab","def"] 以及它将如何对这些数据进行排序以及对这些数据进行排序的逻辑是什么。

【问题讨论】:

  • 单个 Java 集合通常不能支持这些数据的倍数,除非您使用像 List<Object> 这样的东西,这是一个原始集合,不推荐使用。也许将您当前的 Java 代码添加到您的问题中。
  • 嗨@Satish - 蒂姆是对的 - 你正在使用什么集合[或者这是一个假设的......]怀疑它可能是比较.toString()的顺序..
  • @tim,是的,它是一个列表

标签: java sorting collections


【解决方案1】:

当您有某些疑问时,您可以随时尝试:

尝试 #1:让我们对对象列表进行排序

List<Object> list = Arrays.asList('a',2,3,5,'b',"ab","def");
      
Collections.sort(list);

结果:

error: no suitable method found for sort(List<Object>)
      Collections.sort(list);
                 ^
    method Collections.<T#1>sort(List<T#1>) is not applicable
      (inference variable T#1 has incompatible bounds
        equality constraints: Object
        lower bounds: Comparable<? super T#1>)
    method Collections.<T#2>sort(List<T#2>,Comparator<? super T#2>) is not applicable
      (cannot infer type-variable(s) T#2
        (actual and formal argument lists differ in length))
  where T#1,T#2 are type-variables:
    T#1 extends Comparable<? super T#1> declared in method <T#1>sort(List<T#1>)
    T#2 extends Object declared in method <T#2>sort(List<T#2>,Comparator<? super T#2>)

所以,普通的List&lt;Object&gt; 不能按原样排序。

尝试 #2。给定示例中的所有对象都是Comparable,所以让我们尝试对它们进行排序:

List<Comparable> list = Arrays.asList('a',2,3,5,'b',"ab","def");
      
Collections.sort(list);

它也不起作用:

Exception in thread "main" java.lang.ClassCastException: class java.lang.Character cannot be cast to class java.lang.Integer (java.lang.Character and java.lang.Integer are in module java.base of loader 'bootstrap')
    at java.base/java.lang.Integer.compareTo(Integer.java:59)
    at java.base/java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:320)
    at java.base/java.util.ComparableTimSort.sort(ComparableTimSort.java:188)
    at java.base/java.util.Arrays.sort(Arrays.java:1249)
    at java.base/java.util.Arrays.sort(Arrays.java:1436)
    at java.base/java.util.Arrays$ArrayList.sort(Arrays.java:4405)
    at java.base/java.util.Collections.sort(Collections.java:145)

因此,列表中的对象不应该只是Comparable,它们的类型必须是“兼容的”

尝试 #3。使用Object的一些现有方法来比较对象(例如toStringhashCode

List<Object> list = Arrays.asList('a',2,3,5,'b',"ab","def");
      
list.sort(Comparator.comparingInt(Object::hashCode));

System.out.println("Sorted by hashCode: " + list);
      
list.sort(Comparator.comparing(Object::toString));
      
System.out.println("Sorted by toString: " + list);

输出:

Sorted by hashCode: [2, 3, 5, a, b, ab, def]
Sorted by toString: [2, 3, 5, a, ab, b, def]

【讨论】:

  • 感谢您的清晰解释,现在我知道了它是如何工作的。
猜你喜欢
  • 1970-01-01
  • 2023-03-10
  • 2013-11-03
  • 1970-01-01
  • 1970-01-01
  • 2013-06-10
  • 2020-05-14
  • 2016-11-03
  • 1970-01-01
相关资源
最近更新 更多