How to make ArrayList that work as two dimentional array in java?

后端 未结 7 1554
时光说笑
时光说笑 2021-01-23 20:16

I want to make arrayList object in java that work as two dimentional array. My question is how can we access value from specific dimention from arrayList.

in two diment

7条回答
  •  孤城傲影
    2021-01-23 21:04

    List> list = new ArrayList>();
    list.add(new ArrayList());
    list.add(new ArrayList());
    list.get(0).add(5);
    list.get(1).add(6);
    
    for(List listiter : list)
    {
        for(Integer integer : listiter)
        {
            System.out.println("" + integer);
        }
    }
    

    This way you can get the items like

    list.get(1).get(0); //second dimension list -> integer
    

    EDIT:

    Although it is true that you can use a Map if you are trying to use numeric indices for example for each list, like so:

    Map> map = new HashMap>();
    map.put(0, new ArrayList());
    map.put(5, new ArrayList());
    map.get(0).add(new YourObject("Hello"));
    map.get(5).add(new YourObject("World"));
    
    for(Integer integer : map.keySet())
    {
        for(YourObject yourObject : map.get(integer))
        {
             yourObject.print(); //example method
             System.out.println(" ");
        }
    }
    

    Although even then the accessing of Lists would be the same as before,

    map.get(0).get(1); //List -> value at index
    

    Obviously you don't need to use Integers as the generic type parameter, that's just a placeholder type.

提交回复
热议问题