【发布时间】:2013-12-04 09:53:50
【问题描述】:
我已经是第一次在 java 上使用 Map。我正在控制台上创建一个项目,并在其中创建具有此结构的字符串:
String = word1 word2 word3, code; //This code is a number, can be the same as the
// Map's key.
然后,每次创建这样的字符串时,我都会将其保存到地图中。创建一个或多个字符串并将其保存到地图中后,我必须能够在控制台中显示它们,或者删除其中一个。
我遇到的问题是,当向地图添加一个字符串时,会覆盖前一个。
在主类我是这样工作的:
我在地图上添加了一个字符串:
musicmap.add(title, autor, format);
我列出项目:
musicmap.list();
我从地图中删除一个元素:
musicmap.delete(code);
方法 add()、list() 和 delete() 是其他类中这样定义的方法:
Map<Integer, Music> musicMap= new HashMap<Integer, Music>(); //Music is a class
// where is defined a constructor with the
// structure of the strings
public void add(String title, String autor, String format){
int max = 0;
for (Integer mapCode : musicMap.keySet()){
if (mapCode > max){
max = mapCode;
}
}
int newCode = max++;
Music musicItem = new Music(title, autor, format, newCode);
musicMap.put(newCode, musicItem);
}
public void list(){
for (Music item : musicMap.values()){
System.out.println(item.toString());
}
}
public void delete(int code){
musicMap.remove(code);
}
Music 实例只是调用其他类,其中定义了带有音乐列表元素(这些是标题、作者、格式或类型和代码)的构造函数:
public Music(String title, String autor, String type, int code){
this.setTitle(title);
this.setAutor(autor);
this.setType(type);
this.setCode(code);
}
【问题讨论】: