1

Java gurus, thank you for reading my question. I will get straight to the point. When I am looping through a database ResultSet object and updating a LinkedHashMap using put method, all the previously added values are being updated. Key being Columnname and Value being a list of properties for the given column.

        this.colpropmap=new LinkedHashMap<String, LinkedList<String>>();

        LinkedList<String> colproplist=new LinkedList<String>();

        while(crs.next()) {
            colproplist.clear();
            //Debug Statement
            //System.out.println(crs.getString("COLNAME") + " " + crs.getInt("COLNO"));
            colproplist.add(Integer.toString(crs.getInt("COLNO")));
            colproplist.add(crs.getString("DATATYPE"));
            //Debug Statement
            System.out.println("\t" + crs.getString("COLNAME") + ": " + colproplist);
            colpropmap.put(crs.getString("COLNAME"), colproplist);
            System.out.println("\t" + colpropmap);
        }

For each while iteration, I am seeing all the previous keys are being updated with the latest Key's value. Any clue what is going on here ?

EMPID                         : [0, INTEGER(4,0)]
{EMPID                         =[0, INTEGER(4,0)]}
NAME                          : [1, VARCHAR(30,0)]
{EMPID                         =[1, VARCHAR(30,0)], NAME                         =[1, VARCHAR(30,0)]}
SALARY                        : [2, DECIMAL(5,2)]
{EMPID                         =[2, DECIMAL(5,2)], NAME                          =[2, DECIMAL(5,2)], SALARY                        =[2, DECIMAL(5,2)]}
EMPID                         : [0, INTEGER(4,0)]
{EMPID                         =[0, INTEGER(4,0)]}
NAME                          : [1, VARCHAR(25,0)]
{EMPID                         =[1, VARCHAR(25,0)], NAME                          =[1, VARCHAR(25,0)]}
SALARY                        : [2, DECIMAL(5,2)]
{EMPID                         =[2, DECIMAL(5,2)], NAME                          =[2, DECIMAL(5,2)], SALARY                        =[2, DECIMAL(5,2)]}
Raghu
  • 43
  • 1
  • 7
  • 2
    You're overwriting the same list. Change `colproplist.clear();` to `colproplist = new LinkedList<>();` – shmosel Aug 25 '17 at 22:36
  • Thank you @Shmosel, I am a DBA and coding a database utility in java. This completely make sense. I am battling this issue for past couple of hours :-) – Raghu Aug 25 '17 at 23:00

0 Answers0