0

given:

class Widget {
    Object value;
}

interface WidgetMap {
    void put( Widget key, Widget value );
    Widget get( Widget key );
}

... how would I go about implementing WidgetMap using only Widget objects or primitives? Without the use of other classes (toolkits, collections, JDK classes ). Primitive arrays would be allowed, but it would be better to do without them.

4
  • 4
    if this is homework it must be tagged as such, if it isn't just use the collections Commented Jul 26, 2011 at 2:31
  • ... no, but close enough Commented Jul 26, 2011 at 2:41
  • How can you implement anything in java without using jdk classes? Commented Jul 26, 2011 at 2:44
  • 1
    I would think that the source for HashMap/Hashtable would be a huge inspiration here. Commented Jul 26, 2011 at 2:46

1 Answer 1

4

This is a map implemented as a linked list of WidgetMap. It doesn't strike me as terribly efficient, or useful, but it should function. I assume you also want a remove function, but I'll leave that as an exercise. This also assumes you appropriately override the Widget.equals function, though it should be trivial to fix it not to have that requirement.

class BadMap implements WidgetMap{

    private WidgetMap next = null;
    private Widget key = null;
    private Widget val = null;

    public void put(Widget _key, Widget _value){
        if(key == null){
            key = _key;
            val = _value;
        }else if(key.equals(_key)){
            val = _value;
        }else if(next != null){
            next.put(_key, _value);
        }else{
            next = new BadMap();
            next.put(_key, _value);
        }
    }

    public Widget get(Widget _key){
        if(key != null && key.equals(_key)){
            return val;
        }else if(next != null){
            return next.get(_key);
        }else{
            return null;
        }
    }

}

Working example code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.