gpt4 book ai didi

java - 在 Java 中,是否可以将数字拆箱为适当的类型?

转载 作者:行者123 更新时间:2023-11-29 03:14:52 25 4
gpt4 key购买 nike

class Node<T extends Number> implements Comparable<Node<T>>{
private T data;
private Node<T> next;
private Node<T> prev;

public Node(T data){
this.data = data;
next = null;
prev = null;
}

public int compareTo(Node<T> o){
if(o.data > this.data){
return -1;
}else if(o.data < this.data){
return 1;
}else{
return 0;
}
}

我写了上面的代码,当我尝试编译它时,我得到了

    Queue.java:14: error: bad operand types for binary operator '>'
if(o.data > this.data){
^
first type: T
second type: T
where T is a type-variable:
T extends Number declared in class Queue.Node

Queue.java:16: error: bad operand types for binary operator '<'
}else if(o.data < this.data){
^
first type: T
second type: T
where T is a type-variable:
T extends Number declared in class Queue.Node
2 errors

只是为了让您不要被 Queue.node 搞糊涂,Class Node 是嵌入在 Class Queue 中的

所以我猜 Java 不会自动拆箱 Number 但有没有办法做到这一点?

谢谢

最佳答案

Number 类是抽象的,不能像扩展它的类一样使用。

例如:

// this doesnt work
Number a = 22;
Number b = 33;
Number c = a - b; // compile error
if(a > b) // compile error

您需要比较这些 Number 对象的一些值。

// this works
Number a = 22;
Number b = 33;
Number c = a.doubleValue() - b.doubleValue();
if(a.longValue() > b.longValue())

因此,要修复您的代码,您的语句应为 if(o.data.doubleValue() > this.data.longValue())

关于java - 在 Java 中,是否可以将数字拆箱为适当的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27286806/

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