gpt4 book ai didi

Java多态: How to indicate comparison should be made using subclass?

转载 作者:行者123 更新时间:2023-12-02 02:50:28 25 4
gpt4 key购买 nike

介绍性问题来了!以下代码...

public class HelloWorld
{
public static void main(String[] args)
{
ArrayList<Object> A = new ArrayList<Object>();
Integer I = new Integer(3);
Double D = new Double(3.14);

A.add(I);
A.add(D);

if (A.get(0) > 2)
{
System.out.print("Hello World");
}
}
}

...编译失败

bad operand types for binary operator '>'
if (A.get(0) > 2)
^
first type: Object
second type: int

如何表明我希望与子类 Integer 进行比较,而不是与 Object 进行比较?

最佳答案

由于IntegerDouble都扩展了Number,然后将ArrayList重新定义为

ArrayList<Number> A = new ArrayList<Number>();

然后

if (A.get(0).intValue () > 2)

关于Java多态: How to indicate comparison should be made using subclass?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43927625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com