使用Hashmap Java的数组超出界限异常

Dav*_*vid 1 java hashmap

我正在尝试将一个带有char数组的hashmap作为值,将一个字符串作为键.我正在尝试打印出键和值,但不断获取数组超出范围的异常.我不确定问题是什么.(另外我可能会尝试不正确地打印出地图;我有点像其他帖子一样).有人可以帮我解决这个问题.谢谢你的帮助.这是我的代码:

public class MapExample {

     public static void main(String[] args) {

       Map<String,char[]> mp=new HashMap<String, char[]>();

       char[] words = new char[2];
       words[0] = 'a';
       words[1] = 'b';
       words[2] = 'c';

       mp.put("1", words);
       mp.put("2", words);
       mp.put("3", words);

       Set s=mp.entrySet();
       Iterator it=s.iterator();

        while(it.hasNext())
        {           
            Map.Entry m =(Map.Entry)it.next();
            int key=(Integer)m.getKey();
            String value=(String)m.getValue();

            System.out.println("Key :"+key+"  Value :"+value);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Rei*_*eus 7

数组基于零.增加数组大小,words以便可以在索引处分配元素2

char[] words = new char[3];
Run Code Online (Sandbox Code Playgroud)


fge*_*fge 6

   char[] words = new char[2];
   words[0] = 'a';
   words[1] = 'b';
   words[2] = 'c'; <-- HERE
Run Code Online (Sandbox Code Playgroud)

您创建了一个两元素数组,但在其中放入了三个项目.

Java中的数组具有固定大小,一旦初始化就无法修改.

然后:

String value=(String)m.getValue();
Run Code Online (Sandbox Code Playgroud)

这不起作用:a char[]不是String!

你必须:

String value = new String((char[]) m.getValue());
Run Code Online (Sandbox Code Playgroud)

但你应该是你的地图.entrySet(),真的.