views:

33

answers:

1

Goodmorning everybody,

I'm having a little problem with a project for school. We are told to make an Iterator that implements Enumeration over a Hashmap.

So i made this Enumeration:

public Enumeration<Object> getEnumeration() {
        return new Enumeration<Object>() {
            private int itemsDone = 0;
            Collection<Long> keysCollection = getContent().keySet();            
            Long [] keys = keysCollection.toArray(new Long[keysCollection.size()]);


            @Override
            public boolean hasMoreElements() {
                if(itemsDone < getContent().size() +1 ) {
                    return true;
                }else {
                    return false;
                }

            }
            @Override
            public Object nextElement() {               
                return getContent().get(keys[itemsDone++]);
            }
        };
    }

This goes in my Backpack class

public class Backpack extends Item implements Carrier, Enumeration<Object>{

The hashmap is returned by getContent(). The problem now is that eclipse keeps telling me I havent implemented the methods from Enumeration. If I use the quick fix it just adds the hasMoreElements() and nextElement() dummy methods in my class. Somehow it doesn't see these methods in the inner class..

Can anyone help me please? Any help is appreciated.

+1  A: 

Backpack doesn't implement it. The anonymous inner class used in getEnumeration does. If you want Backpack itself to implement Enumeration, it needs to have those methods.

Matthew Flaschen
But then how do I create a method that returns an Enumeration over the contents of that backpack. (And by that I mean over the variabele content that is a Hashmap)I don't want to enumerate over the backpack, but over the content of the hashmap.Somewhere in the code it should say implements Enumeration, right? If yes, where?
Harm De Weirdt
No, you're returning an instance of an [anonymous inner class](http://oopweb.com/Java/Documents/ThinkingInJava/Volume/TIJ310.htm) that implements an interface. In this case, you don't use the `implements` keyword.
Matthew Flaschen
Putting this:public Enumeration<Object> getEnumeration() { return new Enumeration<Object>() {is enough to indicate that my class "implements" the Enumeration or that I provide the users of my class with an Enumeration?
Harm De Weirdt
That method signature indicates that Backpack's getEnumeration method returns an instance of a class that implements `Enumeration<Object>`. Backpack itself doesn't implement it.
Matthew Flaschen
I think I get it now. Thank you very much for the fast help :)
Harm De Weirdt