我需要在教授提供的程序中使用 compareTo()。但该程序包括泛型。该功能存在问题。所以我的问题是我该如何实现它。if(node1.getElement().compareTo(node2.getElement()) < 0)我需要一些解释java.util.Iterator; 因为我需要iteration()在主类中使用。我是 Java 新手。可以自由地向新手解释它。Tnx 伙计们这是整体代码:D https://pastebin.com/mA9igb1t
1 回答

BIG阳
TA贡献1859条经验 获得超6个赞
首先:在您的main
方法中,您不能使用泛型E
. Integer
在您的情况下,您必须使用正确的类型。
比较器问题有两种解决方案:
如果您确定
E
将始终是原始类型(如 Byte、Short、Integer、Long、Float 或 Double)的包装器,您可以声明 SLL,class SLL<E extends Number & Comparable> implements Iterable<E>
这样您if
就可以工作了。SLL
不必实现Comparable
.否则,你可以使用的BigDecimal在
if
BigDecimal node1Value = new BigDecimal(node1.getElement().toString());
BigDecimal node2Value = new BigDecimal(node2.getElement().toString());
if(node1Value.compareTo(node2Value) < 0)
关于迭代器的问题,因为你必须调用.iterator()
你的SLL
对象,这个类必须工具可迭代。
您可以在The Java Tutorials - The Collection Interface上阅读有关迭代器的信息。
我还建议看一下LinkedList 的源代码
添加回答
举报
0/150
提交
取消