管理 Map 中的字符串 [英] Manage strings in Map
问题描述
我已经是第一次在 Java 上使用 Map.我正在控制台上创建一个项目,在其中创建具有以下结构的字符串:
I'm already first time using Map on java. I'm creating a project on the console where I create Strings with this structure:
String = word1 word2 word3, code; //This code is a number, can be the same as the
// Map's key.
然后,每次我创建这样的 String 时,我都会将其保存到 Map 中.在创建一个或多个字符串并将其保存到地图中后,我必须能够在控制台中显示它们,或者删除其中之一.
Then, each time I create a String like this, I save it into a Map. After creating and saving into the map one or more Strings, I have to be able to show them in the console, or to delete one of them.
我遇到的问题是,向地图添加一个字符串时,会覆盖前一个字符串.
在主类中,我是这样工作的:
In the main class I work this way:
我向地图添加一个字符串:
I add a String to the map:
musicmap.add(title, autor, format);
我列出项目:
musicmap.list();
我从地图中删除了一个元素:
I delete one element from the map:
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 实例只是调用其他类,其中定义了一个构造函数,其中包含 Music List 的元素(它们是标题、作者、格式或类型和代码):
The Music instance just calls to other class where is defined a constructor with the elements of the Music List (these are title, autor, format or type and code):
public Music(String title, String autor, String type, int code){
this.setTitle(title);
this.setAutor(autor);
this.setType(type);
this.setCode(code);
}
推荐答案
更改此行int newCode = max++;
到int newCode = max + 1;
您的键值以 1 开头.
Your key value is start with 1.
我希望这会有所帮助.
在您的代码中 newCode = max++
赋值是在增加 max
值之前完成的,这会在通过代码 if (mapCode > max) 获取最大键值时产生问题
不执行此条件,因为两者每次都具有相同的值零 (0).
Edit :
In your code newCode = max++
assignment is done before increment the max
value, which create problem in getting you max key value by code if (mapCode > max)
this condition is not execute because both have same value zero (0) every time.
这篇关于管理 Map 中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!