Reputation: 86
I m working on populating a list dynamically with dynamic rows and columns and showing them in UI. All have been done accurately but i m unable to get value from a specified row and column e.g. row 4 and column 3. Code is as under:-
public LiveRangeService() {
tableData = new ArrayList< Map<String, ColumnModel> >();
//Generate table header.
tableHeaderNames = new ArrayList<ColumnModel>();
for (int j = 0; j < 10; j++) {
tableHeaderNames.add(new ColumnModel("header "+j, " col:"+ String.valueOf(j+1)));
}
//Generate table data.
for (int i = 0; i < 8; i++) {
Map<String, ColumnModel> playlist = new HashMap<String, ColumnModel>();
for (int j = 0; j < 10; j++) {
playlist.put(tableHeaderNames.get(j).key, new ColumnModel(tableHeaderNames.get(j).key,"row:" + String.valueOf(i+1) +" col:"+ String.valueOf(j+1)));
}
tableData.add(playlist);
}
try {
System.out.println( "Table Data Size " + tableData.size() );
System.out.println( "Value Of Row 1 Col 2: " + tableData.get(1).get(2) );
} catch (Exception e) {
System.out.println( "Error!! " + e.getMessage() );
}
}
may some body pls help me in understanding this chunk of code. Error occurs on the following line:-
System.out.println( "Value Of Row 1 Col 2: " + tableData.get(1).get(2) );
Upvotes: 0
Views: 165
Reputation:
tableData = new ArrayList< Map<String, ColumnModel> >();
you are storing maps in list and this map is of generic means key in map is String.
tableData.get(1).get(2)
This above line get(1) will give you first Map object. then get(2), means you are passing Integer as key to fetch value from map but your map needs String as key.
Its map and value can be retrieved using key and not based on index like arrayList. so you are getting error
pass something like
tableData.get(1).get(<some string key>)
it should work
Upvotes: 2
Reputation: 86
Fianlly with the help of LHCHIN, the key was header 0, header 1 etc and it worked great. finally i wrote: tableData.get(1).get("header 2").getValue() and it worked perfectly.
Upvotes: 0
Reputation: 767
Java counts starting from 0.
tableData.get(0).get(0)
will get the element at row 1, and column 1. The ArrayList
containing Map
s starts from 0. However, tableData.get(tableData.size())
will throw an error, as it will contain the number of elements in the ArrayList. (So, if an array had 3 elements, tableData.size()
would return 3 and you would be able to call for it by calling for tableData.get(2)
)
tableData.get(1).get(2)
will get the element at row 2, and column 3.
To get the value of the element at row 1, column 2, call tableData.get(0).get(1)
.
Upvotes: 0