我是Java Collections的新手。我正在浏览Map,所以请告诉我就像java提供了Map一样,我们也可以制作自己的Map吗?我们假设一张名为MineMap
的地图。请告诉我如何实现这一目标。我在谷歌上搜索,我发现了这样的事情:
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));
}
}
}
但我需要一些更简单的实现。
答案 0 :(得分:5)
你提到你是初学者,想要实现你自己的地图。在初学者级别编写地图还为时过早。集合框架已经为多种数据类型提供了优化且经过验证的实现。理解这些而不是重新发明轮子是很重要的。
您可以轻松获取Java库源,并尝试了解它们是如何实现集合类的。这是最先进的发展,涵盖了许多细节。
关于实施。
然而,你所发现的东西不能直接归类为地图。毫无疑问,类似的事情。
您可能希望编写实现,例如包含上述功能。
// Hash map java library defined as follows.
public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
// Hence, you may want to write this.
public class MyMap<K,V>
extends AbstractMap<K, V> // May skip this
implements Map<K,V>, Cloneable, Serializable // important
{
//Now it will ask to write all the methods which are defined in Map interface.
//These are minimum methods required for Map operations.
}