java - Problems with implementing a sorted map -


i'm trying implement sorted hash map , have 1 problem. let me describe situation first, 1 understand what's going on.

i defined interface called map. looks this

public interface map<k extends comparable<k>, v>  {         /*** state information ***/ public boolean isempty(); public int size(); public boolean contains(k key);         /*** main operations ***/ public void insert(k key, v value); public v get(k key); public v delete(k key); 

}

and defined class called sortedmap implements interface. in class have nested static class called item acts wrapper. here is

private static class item<k extends comparable<k>, v> implements comparable<item<k, v>> {     private k key;     private v value;      item(k key, v value) {         this.key = key;         this.value = value;     }      @override     public string tostring() { return string.format("%s=%s", key.tostring(), value.tostring()); }      public int compareto(item<k, v> item) {         if (key.compareto(item.key) > 0) return 1;         else if (key.compareto(item.key) < 0) return -1;         else return 0;     } } 

and store objects of class use red black bst underlying storage system.

private redblackbst<item<k, v>> storage = new redblackbst<>(); 

my red black bst can store 1 item (item<k, v> in case) per node, stores 2 others.

public final class redblackbst<t extends comparable<t>> { private node<t> root; ......... // rest of } 

as know map cannot have duplicate keys, in insert() method first have check whether contains key , when delegate task red black bst storage.contains() can't pass key only, have pass item. problem arises. there way solve problem without creating yet red black tree might tree<k, v>?

it's true map, cannot have duplicate key don't have call contains() in insert(). in jdk, behavior of insert() equivalent method - put() if key exists it's replaced new key. can assume key unique , new , go on insert it. if somehow in place want store find key exists there can either replace corresponding value; or can throw exception, depends on what's desired behavior.

there sortedmap interface in jdk , treemap implementation based on red black tree.


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -