HashMap不复制对象

Cri*_*ìna -1 java arrays hashmap

在Java中我有一个ResultSet对象,我用它来填充HashMap对象,这样:

        rs = db.executeQuery(query);
        rs.last();
        rows = rs.getRow();
        rs.beforeFirst();
        String current;
        String[] current_columns = new String[rows];
        int x;
        for(int i=0; i<n_col; i++){ //scroll columns
            x=0;
            while(rs.next()){ // scroll rows
                current = rs.getString(columns[i]);
                current_columns[x++] = current;
            }

            //a little output debug
            System.out.print("hm.put("+columns[i]+", {");
            for(int j=0; j<current_columns.length; j++)
                System.out.print(current_columns[j]+" ");
            System.out.println("});");
            //end of output debug

            hm.put(columns[i], current_columns);

            rs.beforeFirst();

        }
Run Code Online (Sandbox Code Playgroud)

输出调试打印:

hm.put(a,{a1 a2});

hm.put(b,{b1 b2});

所以,如果我写指令hm.get("a")它应该返回数组字符串{"a1","a2"},而如果我写hm.get("b")它应该返回我的数组string {"b1","b2"}.

但是,实际上,当我尝试获取值时,无论密钥如何,hashmap总是返回我放入的最后一个数组.所以如果我写下说明:

System.out.println(hm.get("a")[0]);
System.out.println(hm.get("b")[0]);
Run Code Online (Sandbox Code Playgroud)

它打印:

B1

B1

为什么hashmap有这种行为?问题出在哪儿 ?

Dic*_*ici 6

你总是使用相同的阵列,所有的按键都映射到同一个对象,你应该将它声明循环,不在外面.

    int x;
    for(int i=0; i<n_col; i++){ 
        // This time you declare a NEW array each time
        String[] current_columns = new String[rows];
        x=0;
        while(rs.next()){ 
            current = rs.getString(columns[i]);
            current_columns[x++] = current;
        }

        System.out.print("hm.put("+columns[i]+", {");
        for(int j=0; j<current_columns.length; j++)
            System.out.print(current_columns[j]+" ");
        System.out.println("});");

        hm.put(columns[i], current_columns);

        rs.beforeFirst();
    }
Run Code Online (Sandbox Code Playgroud)