Adobe Interview Question
Applications DevelopersCountry: United States
Interview Type: Written Test
public class OrderedHashtable {
private Hashtable<String, String> internalHashTable = new Hashtable<String, String>();
private List<String> orderedKeyList = new ArrayList<String>();
public void addToHashTable(String key, String value) {
orderedKeyList.add(key);
internalHashTable.put(key, value);
}
public String getValue(String key) {
return internalHashTable.get(key);
}
public List<String> getKeys() {
return orderedKeyList;
}
}
public static void main(String[] args) {
OrderedHashtable orderedHashtable = new OrderedHashtable();
orderedHashtable.addToHashTable("a", "1");
orderedHashtable.addToHashTable("b", "2");
orderedHashtable.addToHashTable("c", "3");
orderedHashtable.addToHashTable("e", "6");
orderedHashtable.addToHashTable("f", "22");
orderedHashtable.addToHashTable("g", "100");
List<String> keys = orderedHashtable.getKeys();
for (String key : keys) {
System.out.println(orderedHashtable.getValue(key));
}
}
create Map<String, String> treeMap = new TreeMap<String, String>(unsortMap);
it will create sorted map from unsorted.
Please let me know if any issue concern.
TreeMap will have higher time complexity for search around O(logn). While hashtable has a complexity of O(1), compromising on search capability is not good. Ideally, implement a linked list wrapper over hashtable, so as in an element get inserted in hashtable, it also gets inserted in linked list, if it is removed from hashtable then it is also removed from linked list. Although an additional space is compromised. Also this question is about ordering of insertion and not about sorted order.
This is Analogous to Java's LinkedHashMap. Just create a LinkedList structure and attach new nodes (elements) as they are added, it's going to be in added order.
- Aasen May 30, 2013