public class MyMap<K,V>
{
private class MapNode<K,V>
{
K key;
V value;
MapNode<K,V> next;
public MapNode(K key, V value)
{
this.key = key;
setValue(value);
}
public void setValue(V value)
{
this.value = value;
}
public V getValue()
{
return value;
}
public K getKey()
{
return key;
}
public void setNext(MapNode<K,V> next)
{
this.next = next;
}
public MapNode<K,V> getNext()
{
return next;
}
}
private MapNode<K,V> head;
private MapNode<K,V> tail;
private int size;
public MyMap()
{
head = null;
tail = null;
}
private boolean canAdd(K key, V value)
{
MapNode<K,V> temp = head;
while (temp !=null)
{
if (temp.getKey().equals(key))
return false;
temp = temp.next;
}
return true;
}
public V put(K key, V value)
{
if (!canAdd(key, value))
{
System.err.println("This key is already here.");
return value;
}
MapNode<K,V> temp = head;
if (head == null && tail == null)
{
head = new MapNode(key, value);
tail = head;
size++;
return value;
}
else if (head != null && head == tail)
{
temp.setNext(new MapNode(key, value));
size++;
return value;
}
else
{
while (temp.next != tail)
{
temp = temp.next;
}
tail = new MapNode(key, value);
temp.setNext(tail);
size++;
return value;
}
}
public V get(K key)
{
if (head == null)
return null;
MapNode<K,V> temp = head;
while (temp != null)
{
if (temp.getKey().equals(key))
return temp.getValue();
temp = temp.next;
}
return null;
}
public String toString()
{
if (head == null)
return "[]";
MapNode<K,V> temp = head;
String str = "[";
if (head != null && head == tail)
{
str = str + temp.getKey().toString() + "=" + temp.getValue().toString() + "]";
return str;
}
while (temp != tail)
{
str = str + temp.getKey().toString() + "=" + temp.getValue().toString() + ",";
temp = temp.next;
}
str = str + temp.getKey().toString() + "=" + temp.getValue().toString() + "]";
return str;
}
public int size()
{
return size;
}
public static void main(String[] args)
{
MyMap<String,String> tester = new MyMap<String,String>();
tester.put("Bob", "Mike");
tester.put("Ben", "John");
tester.put("Ruth", "Joe");
System.out.println(tester.toString());
System.out.println(tester.get("Ruth").toString());
}
}