简体   繁体   中英

Accessing Data From ArrayList

I m working on populating a list dynamically with dynamic rows and columns and showing them in UI. All have been done accurately but im unable to get value from a specified row and column eg 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) );

the result shown on page

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

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) .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM