0
我是Java Collections的新手。我正在通過Map,所以請告訴我,就像java提供了Map一樣,我們是否也可以製作自己的Map?我們來看一個名爲MineMap
的地圖。請告訴我如何做到這一點。我在做谷歌搜索,我發現了這樣的事:Java地圖實現
public interface MyMap
{
public void put(Object key,Object value);
public Object get(Object key);
public int size();
public Set keySet();
public Set entrySet();
public interface MyEntry
{
public Object getKey();
public Object getValue();
}
}
及其實施:
class MySimpleMap implements MyMap
{
private ArrayList keys;
private ArrayList values;
private int index;
public MySimpleMap()
{
keys=new ArrayList();
values=new ArrayList();
index=0;
}
public void put(Object key,Object value)
{
keys.add(key);
values.add(value);
index++;
}
public Object get(Object key)
{
int i=keys.indexOf(key);
if (i>=0)
return values.get(i);
else
return null;
}
public int size()
{
return index;
}
public Set keySet()
{
HashSet set=new HashSet();
set.addAll(keys);
return set;
}
//Nested class starts...
class MySimpleEntry implements MyMap.MyEntry
{
Object key;
Object value;
public MySimpleEntry(Object k,Object v)
{
key=k;
value=v;
}
public Object getKey()
{
return key;
}
public Object getValue()
{
return value;
}
}// Nested class ends.
public Set entrySet()
{
HashSet set=new HashSet();
for (int i=0;i<index;i++)
{
Object k=keys.get(i);
Object v=values.get(i);
MySimpleEntry temp=new MySimpleEntry(k,v);
set.add(temp);
}
return set;
}
}
,最後這個是使用這個類:
class MyMapDemo
{
public static void main(String arr[])
{
MySimpleMap map=new MySimpleMap();
map.put("Amit","Java");
map.put("Rahul",".Net");
map.put("Nitin","SQT");
map.put("Ajay","PHP");
map.put("Raman","Java");
System.out.println("There are "+map.size()+" elemenets in the map...");
System.out.println("contents of Map...");
Set s=map.entrySet();
Iterator itr=s.iterator();
while(itr.hasNext())
{
MyMap.MyEntry m=(MyMap.MyEntry) itr.next();
System.out.println(m.getKey()+"\t"+m.getValue());
}
Scanner in=new Scanner(System.in);
System.out.println("Enter Name to find out course, ctrl+c to terminate...");
while(true)
{
System.out.println("Name:");
String n=in.nextLine();
System.out.println("Course is:"+map.get(n));
}
}
}
,但我需要一些簡單的實現。
爲什麼和如何更簡單?你真的需要這些? – simchona 2012-04-17 03:23:24
更簡單?你的實現實際上太簡單了,例如,它缺少對密鑰的唯一性檢查。 – trutheality 2012-04-17 03:25:15