java问号表达式,无法在Java中使用两个问号形成类型的表达式

本文讨论了在Java代码中遇到类型匹配问题的场景,具体表现为尝试将不同类型的对象传递给期望相同类型参数的方法。解决方案是确保传递的对象符合方法签名的要求,即使用相同类型的泛型。示例中指出,可以使用共同基类或接口来解决此类问题,如将两个不同的类型(Paired2和Paired3)转换为它们都实现的公共类型。
摘要由CSDN通过智能技术生成

I can neither compile nor refactor the following code to work:

public class DoubleQuestionMark {

public static class Paired1

{

}

public static class Paired2

{

}

public static class Paired3

{

}

// regard it as third party method, not allowed to change signature

public static void perform(Paired1, Paired3> argument) {

}

public static void main(String[] args) {

Paired2 p2 = new Paired2<>();

Paired3 p3 = new Paired3<>();

Paired1, Paired3> p1 = new Paired1<>();

perform(p1); // cannot be applied to given class

}

}

How to prepare an object, acceptable by perform method?

解决方案

You are trying to pass two different types for the same type parameter S.

Paired1, Paired3> Both S must be of the same type:

So this will work:

Paired1, Paired3> p1 = new Paired1<>();

perform(p1);

But this will not:

Paired1, Paired3> p1 = new Paired1<>();

perform(p1);

If you need to pass two different numeric types, both Integer and Double extend Number. So you can use:

Paired1, Paired3> p1 = new Paired1<>();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值