How to create a class that implements java.util.collections

后端 未结 6 779
深忆病人
深忆病人 2021-02-10 09:46

I am trying to create a class say MyStack that would implement a java.util.collections class. MyStack will override some methods of the collections cl

相关标签:
6条回答
  • 2021-02-10 10:25

    Is defining a stack what you really want to achieve? If so, then go ahead and define it without even implementing Collection interface - it will be OK for simple cases. Or use an existing class - java.util.Stack.

    0 讨论(0)
  • 2021-02-10 10:28

    When we implement Collection along with we must implement Iterator<E> also. Which is use to iterate over the item on which you want.

    0 讨论(0)
  • 2021-02-10 10:29

    Make sure to throw on a <E> specification on your class as well:

    public class MyStak<E> implements java.util.Collection<E>
                       ^^^
    

    If you want to make life easier on yourself try sub-classing AbstractCollection instead of implementing Collection directly. It provides reasonable default implementations for most of the methods to minimize the amount of code you need to write.

    java.util

    Class AbstractCollection<E>

    This class provides a skeletal implementation of the Collection interface, to minimize the effort required to implement this interface.

    To implement an unmodifiable collection, the programmer needs only to extend this class and provide implementations for the iterator and size methods. (The iterator returned by the iterator method must implement hasNext and next.)

    To implement a modifiable collection, the programmer must additionally override this class's add method (which otherwise throws an UnsupportedOperationException), and the iterator returned by the iterator method must additionally implement its remove method.

    The programmer should generally provide a void (no argument) and Collection constructor, as per the recommendation in the Collection interface specification.

    0 讨论(0)
  • 2021-02-10 10:31

    And one recommendation, if you plan to implement your own collection interface consider extending corresponding abstract class, but not implementing interface itself, cause abstract classes implement methods general to the interface. Look at: AbstractCollection, AbstractSet, AbstractList

    0 讨论(0)
  • 2021-02-10 10:38

    You were VERY close!

    You just need to define E in your subclass as well:

    public class MyStak<E> implements java.util.Collection<E>
    

    The idea is that you could have a subclass with, say, <E, F, G>, and you implement two different interfaces, one using E, one using F. That, or MyStak could be specialized and use a specific class for Collection, instead of a generic E.

    0 讨论(0)
  • 2021-02-10 10:41

    Instead of:

    public class MyStak implements java.util.Collection<E>{
    

    try:

    public class MyStak<E> implements java.util.Collection<E>{
    
    0 讨论(0)
提交回复
热议问题