扩展和实现的 Java 规则
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2441297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java rule for extends and implements
提问by Rohit Banga
While coding I created a class that extends ArrayList<>and implements Iterable<>. The code is :
在编码时,我创建了一个类,extends ArrayList<>并且implements Iterable<>. 代码是:
public class Testclass extends ArrayList<Object>, implements Iterable<Object> { }
Netbeans reported an error:
Netbeans 报错:
'{' expected
How to prevents this?
如何防止这种情况?
回答by BalusC
From the comments:
来自评论:
error is '{' expected
code is this
public class Testclass extends ArrayList<Object>, implements Iterable<Object> { }
错误是“{”预期
代码是这样的
public class Testclass extends ArrayList<Object>, implements Iterable<Object> { }
Remove that comma ,. It doesn't belong there. It's just a syntax error.
删除那个逗号,。它不属于那里。这只是一个语法错误。
In the future, please readthe error message. If you can't interpret it, even not after a little Googling, just ask it here, complete with the entire error message and the code which caused it. This way you will get better suited answers sooner than guessing randomly for the cause ;)
以后,请阅读错误消息。如果您无法解释它,即使经过一点谷歌搜索也无法解释,只需在此处提问,并附上完整的错误消息和导致错误的代码。通过这种方式,您将比随机猜测原因更快地获得更合适的答案;)
回答by Thilo
ArrayList does not implement Iterator. Maybe you mean Iterable?
ArrayList 没有实现迭代器。也许你的意思是 Iterable?
Anyway, it is not a problem to implement an interface that a superclass already implements (it is just redundant).
无论如何,实现一个超类已经实现的接口不是问题(它只是多余的)。
What error are you getting? It seems to be about something else. If you are using generics, did you make sure the types match on superclass and interface?
你遇到了什么错误?它似乎是关于别的东西。如果您使用泛型,是否确保超类和接口的类型匹配?
Also, it seems to be against the spirit of the Collection and Iterator interfaces to have an object that is both at the same time. At the very least, it is quite confusing.
此外,同时拥有一个对象似乎有悖于 Collection 和 Iterator 接口的精神。至少,它是相当混乱的。
回答by kiwicptn
For a class that extends ArrayList and implements Iterator, you need three methods:
对于扩展ArrayList并实现Iterator的类,需要三个方法:
public boolean hasNext()
public Object next()
public void remove()
回答by Mikel
Remove the coma between and implements
消除和工具之间的昏迷
I do not know what you are doing but you do not want a class that extends ArrayList and implements iterator.
我不知道你在做什么,但你不想要一个扩展 ArrayList 并实现迭代器的类。
Just implement List (or even Collection if you can). If someone wants the iterator they can just call the method yourList.iterator(). You can even return your custom iterator if that is what you really want.
只需实现 List (如果可以,甚至是 Collection)。如果有人想要迭代器,他们可以调用 yourList.iterator() 方法。如果这是您真正想要的,您甚至可以返回您的自定义迭代器。

![java 根据 hashMap 值对 HashMap 列表进行排序 [不是键]](/res/img/loading.gif)