Reputation: 1637
Problem
I am trying to create something like a multi-dimensional associate array using HashMaps in Java. For some reason i am getting similar results for all elements inside the Map. Following is the code i am using
private HashMap<String, HashMap<String, String>> getNullableColumns(Connection dbConn, String resource) throws SQLException {
HashMap<String, HashMap<String, String>> nullableColumns = new HashMap<String, HashMap<String, String>>();
HashMap<String, String> column = new HashMap<String, String>();
DatabaseMetaData dm = dbConn.getMetaData();
ResultSet rsColumns = dm.getColumns(null, null, getTable(resource), null);
while( rsColumns.next( ) )
{
String type = rsColumns.getString("TYPE_NAME");
String nullable1 = rsColumns.getString("NULLABLE");
String nullable2 = rsColumns.getString("IS_NULLABLE");
String dataType = rsColumns.getString("DATA_TYPE");
String columnName = rsColumns.getString("COLUMN_NAME");
column.put("type", type);
column.put("nullable", nullable1);
nullableColumns.put(columnName, column);
}
return nullableColumns;
}
Explaination:
I get the right result in column HashMap, but when i put each on of them into nullableColumns, all the elements have the same property at the end, for example all fields are type varchar and nullable is 0. It looks like i am somehow overriding the result at the end, but where i am making this mistake i couldn't figure out.
Any suggestion please?
Upvotes: 1
Views: 153
Reputation: 394146
You are adding the same HashMap
instance
HashMap<String, String> column = new HashMap<String, String>();
multiple times to the outer Map
, so all the values in the nullableColumns
Map
are the same HashMap
instance.
You should create a new HashMap
in each iteration of the loop :
while (rsColumns.next( ) )
column = new HashMap<String, String>();
String type = rsColumns.getString("TYPE_NAME");
String nullable1 = rsColumns.getString("NULLABLE");
String nullable2 = rsColumns.getString("IS_NULLABLE");
String dataType = rsColumns.getString("DATA_TYPE");
String columnName = rsColumns.getString("COLUMN_NAME");
column.put("type", type);
column.put("nullable", nullable1);
nullableColumns.put(columnName, column)
}
Upvotes: 4