0

是否可以将未知数据类型与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;
  }
}
4

1 回答 1

2

我可能会做这样的事情(我假设 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;
}
于 2013-04-26T05:29:47.860 回答