【问题标题】:Incomparable types capture and int in Java streams allMatch()Java流中无与伦比的类型捕获和int allMatch()
【发布时间】:2018-05-02 08:43:03
【问题描述】:

我有 X509 证书。我正在尝试从中提取所有 SAN。之后,我想确保 SAN 的类型为 dNSName - 即列表中的第一个条目应该是值为 2 的整数。参考-https://docs.oracle.com/javase/7/docs/api/java/security/cert/X509Certificate.html#getSubjectAlternativeNames()

下面的表达式编译失败,说“Incomparable types capture and int”

certificate.getSubjectAlternativeNames().stream().allMatch(x -> x.get(0) == 2)

但是,下面的表达式返回 True。

certificate.getSubjectAlternativeNames().stream().allMatch(x -> x.get(0).toString().equals("2"))

我不想将其转换为字符串,然后将其与字符串匹配。我只想在这里进行整数比较。我该怎么做?

【问题讨论】:

    标签: java java-8 x509certificate x509


    【解决方案1】:

    我只想在这里进行整数比较。

    您应该能够简单地在List 的第一个元素上调用Object#equals:

    certificate.getSubjectAlternativeNames()
               .stream()
               .allMatch(x -> x.get(0).equals(2))
    

    因为List 的泛型类型是捕获类型?,编译器将无法推断其中Object 的类型,并且不允许您将其与原始(直接)。

    List<List<?>> list = List.of(List.of(1, 2, 3));
    
    System.out.println(list.stream().allMatch(x -> x.get(0).equals(1)));
    

    输出:

    true
    

    【讨论】:

    • 补充一点:Lists 只能存储对象类型,不能存储原始类型。只有在可以拆箱对象的情况下,才可以使用== 将对象与原语进行比较。为此,对象的类型必须是静态可推导出为盒装原始类型之一(Integer、Long、...)
    • @WorldSEnder 但是如果不能静态推断出集合元素的类型是Integer,那么使用equals 是非常危险的,因为如果类型不匹配,它会默默地失败,例如如果元素实际上是 Long 值。更好的选择是x -&gt; (Integer)x.get(0) == 1,如果关于元素类型的假设是错误的,它会很明显。
    猜你喜欢
    • 2013-02-18
    • 1970-01-01
    • 2018-12-09
    • 2013-04-25
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多