如何将 compareTo 用于泛型。(<E>, <整数>...)

我需要在教授提供的程序中使用 compareTo()。但该程序包括泛型。该功能存在问题。所以我的问题是我该如何实现它。

if(node1.getElement().compareTo(node2.getElement()) < 0)

我需要一些解释java.util.Iterator; 因为我需要iteration()在主类中使用。我是 Java 新手。可以自由地向新手解释它。Tnx 伙计们

这是整体代码:D https://pastebin.com/mA9igb1t


慕妹3146593
浏览 234回答 1
1回答

BIG阳

首先:在您的main方法中,您不能使用泛型E.&nbsp;Integer在您的情况下,您必须使用正确的类型。比较器问题有两种解决方案:如果您确定E将始终是原始类型(如 Byte、Short、Integer、Long、Float 或 Double)的包装器,您可以声明 SLL,class SLL<E extends Number & Comparable> implements Iterable<E>这样您if就可以工作了。SLL不必实现Comparable.否则,你可以使用的BigDecimal在ifBigDecimal node1Value = new BigDecimal(node1.getElement().toString());BigDecimal node2Value = new BigDecimal(node2.getElement().toString());&nbsp;if(node1Value.compareTo(node2Value) < 0)关于迭代器的问题,因为你必须调用.iterator()你的SLL对象,这个类必须工具可迭代。您可以在The Java Tutorials - The Collection Interface上阅读有关迭代器的信息。我还建议看一下LinkedList 的源代码
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java