我是 Java 集合的新手。我正在通过地图,所以请告诉我,就像java提供地图一样,我们也可以制作自己的地图吗?假设一个名为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));
}
}
}
但我需要一些更简单的实现。