【问题标题】:Java: sort List from index to indexJava:从索引到索引排序列表
【发布时间】:2012-03-27 09:31:49
【问题描述】:

对于数组,有一个特殊的函数可以将数组的一部分从索引排序到索引:

Arrays.sort(Object[] a, int fromIndex, int toIndex)

对于List< T>

还有排序功能

Collections.sort(List<T> list)

不幸的是,没有接受fromIndextoIndex 参数的变体。

我知道我可以通过申请来解决这个问题

  • 将列表转换为数组并应用Arrays.sort,然后将其转换回列表
  • 将由 fromIndex 索引到 toIndex 的列表条目复制到新列表(使用list.subList(fromIndex, toIndex)),对其进行排序并覆盖旧列表条目

但我希望有更漂亮的方法来做到这一点。

【问题讨论】:

  • 嘿伙计,转换为数组并不丢人,享受一些额外的功能,然后再转换回来 ;)

标签: java arrays list sorting


【解决方案1】:

只需使用 .subList() 将“支持”视图放到主列表中,然后调用 sort。子列表是“直写”的,因此更改会反映在原始列表中。

List<Integer> foo = Arrays.asList(5,3,1,6,2,1);
Collections.sort(foo.subList(0, 3)); // sort first 3 elements 
System.out.println(foo);
Collections.sort(foo.subList(3, 6)); // sort last 3 elements
System.out.println(foo);

输出

[1, 3, 5, 6, 2, 1]
[1, 3, 5, 1, 2, 6]

【讨论】:

    【解决方案2】:

    您可以在原始列表中使用subList(),然后对子列表进行排序,它将反映在您的原始列表中,而无需回信。

    【讨论】:

      【解决方案3】:

      将由fromIndex索引到toIndex的列表条目复制到一个新的List (通过使用 list.subList(fromIndex, toIndex)),对其进行排序并覆盖 旧列表条目

      不,调用 list.subList 时没有对象副本。函数 subList 创建一个由原始列表支持的视图。仅参考副本;没有实际的对象副本。

      对视图的任何操作(排序)都会反映在原始列表中。

       public static void main(String[] args) throws Exception {
          List<Integer> list = Arrays.asList(1, 9, 8 ,7, 2, 3, 4);
      
          // [9, 8 ,7] => [7, 8, 9]
          sortList(list, 1, 4);
      
          System.out.println(list);       // [1, 7, 8, 9, 2, 3, 4]
        }
      
        public static <T extends Comparable<T>> void sortList(
            List<T> list, int fromIndex, int toIndex) {
          Collections.sort(list.subList(fromIndex, toIndex));
        }
      

      【讨论】:

        【解决方案4】:

        查看 Oracle 文档,CollectionsList 根本不包含此功能,就像 Arrays 一样。如果我必须在您的两个建议中做出选择,我会使用List.subList(fromIndex, toIndex)) 来实施第二个。

        这是文档:http://docs.oracle.com/javase/7/docs/api/java/util/List.html
        http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html
        http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-08-20
          • 1970-01-01
          • 1970-01-01
          • 2023-03-30
          • 2012-12-20
          • 1970-01-01
          • 2020-02-07
          相关资源
          最近更新 更多