gpt4 book ai didi

java - 将 "unknown"值与 int 进行比较

转载 作者:行者123 更新时间:2023-12-02 07:04:49 24 4
gpt4 key购买 nike

是否可以将未知数据类型与int进行比较。我正在尝试编写一个获取最大节点的函数,但数据类型是 E 而不是 int

到目前为止我的代码是..

public E getMax() {
if (isEmpty()) {
throw new NoSuchElementException(" error " ) ;
} else {
Node n = first;

E x ;
int max = 0 ;
while (n!=null) {
if (n.data > x) {
max = n.data;
}
}
return x;
}
}

最佳答案

我可能会做这样的事情(我假设 n.data 是 E 类型)。

对于通用的,我会:

class YourClass<E extends Comparable<? super E>>

然后您的 getMax 方法将类似于:

public E getMax()
{
if (isEmpty())
throw new NoSuchElementException(" error " );

Node n = first;

E max = n.data;

while (n != null)
{
if (n.data.compareTo(max) > 0) // if n.data > max
max = n.data;

n = n.next; // move to the next node
}

return max;
}

关于java - 将 "unknown"值与 int 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16229182/

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