zoukankan      html  css  js  c++  java
  • Comparator.reversed()编译类型推断失败

    错误描述

    import java.util.Arrays;
    import java.util.Comparator;
    import java.util.List;
    
    public class Client {
    
      public static void main(String[] args) {
        List<String> list = Arrays.asList("hello", "world", "hello cat");
        //works
        list.sort(Comparator.comparingInt(String::length));
        //works
        list.sort(Comparator.comparingInt(x -> x.length()));
        //works
        list.sort(Comparator.comparingInt((String x) -> x.length()).reversed());
        //not works
        list.sort(Comparator.comparingInt(x -> x.length()).reversed());
        System.out.println(list);
      }
    
    }
    

    /**
         * Returns a comparator that imposes the reverse ordering of this
         * comparator.
         *
         * @return a comparator that imposes the reverse ordering of this
         *         comparator.
         * @since 1.8
         */
        default Comparator<T> reversed() {
            return Collections.reverseOrder(this);
        }
    

    前面几种情况可以正常编译,第四种情况编译不通过,这种情况编译器不能推断出字符串类型,只能当做Object类型。

    解决方法

    import java.util.Arrays;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    
    public class Client {
    
      public static void main(String[] args) {
        List<String> list = Arrays.asList("hello", "world", "hello cat");
        //works
        list.sort(Comparator.comparingInt((String x) -> x.length()).reversed());
        //works
        list.sort(Collections.reverseOrder(Comparator.comparingInt(x -> x.length())));
        //works
        list.sort(Comparator.comparing(x -> x.length(), Comparator.reverseOrder()));
        System.out.println(list);
      }
    
    }
    

    显式声明类型或者使用Collections.reverseOrder()方法。

    参考

    Comparator.reversed() does not compile using lambda
    Comparator.reversed() should be usable in static context

  • 相关阅读:
    pandas read_excel 产生 Unnamed:0 列
    python 打印输出百分比符号%
    python 内存回收
    python 编码问题
    python 判断 txt 编码方式
    python 二维list取列
    python 两个list 求交集,并集,差集
    pandas Timestamp的用法
    Dataframe 取列名
    Dataframe 新增一列, apply 通用方法
  • 原文地址:https://www.cnblogs.com/strongmore/p/14643400.html
Copyright © 2011-2022 走看看