【问题标题】:Manage strings in Map管理 Map 中的字符串
【发布时间】: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);

}

【问题讨论】:

    标签: java string map arraylist


    【解决方案1】:

    更改此行
    int newCode = max++;

    int newCode = max + 1;

    你的键值是从 1 开始的。

    我希望这会有所帮助。

    编辑:
    在您的代码中,newCode = max++ 赋值是在增加 max 值之前完成的,这会在通过代码 if (mapCode &gt; max) 获取最大键值时产生问题,因为两者每次都具有相同的零 (0) 值,所以不会执行此条件。

    【讨论】:

      【解决方案2】:

      int newCode = max++; 更改为int newCode = max + 1;

      int newCode = max++; 更改为int newCode = ++max;

      目前您所有的密钥都是0。这是一个可怕的错误,因为它看起来是正确的,但这里的分配 int newCode = max++; 发生在添加 max++ 之前。

      我认为您不需要Map,因为您正在模拟ArrayList 的行为。将您的实现更改为如下所示:

      private List<Music> list = new ArrayList<Music>();
      
      public void add(String title, String autor, String format){
          Music musicItem = new Music(title, autor, format, newCode);
          list.add(musicItem);
      }
      

      您将通过这种方式获得索引。一般避免使用++-- 运算符。

      【讨论】:

        猜你喜欢
        • 2020-10-21
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-09
        相关资源
        最近更新 更多