如何使作为Java的2维数组ArrayList的工作? [英] How to make ArrayList that work as two dimentional array in java?

查看:392
本文介绍了如何使作为Java的2维数组ArrayList的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要让ArrayList对象在java中这两个二维数组工作。我的问题是我们如何能够从特定的ArrayList渔政访问值。

两个二维数组,如果我想访问值,那么它可以为m [I] [J]。

但在ArrayList中我该怎么办呢?


解决方案

 列表<名单,LT;整数GT;>名单=新的ArrayList<名单,LT;整数GT;>();
list.add(新的ArrayList<整数GT;());
list.add(新的ArrayList<整数GT;());
list.get(0)。新增(5);
list.get(1)。新增(6);对于(列表<整数GT; listiter:名单)
{
    对于(整数整数listiter)
    {
        的System.out.println(+整数);
    }
}

这样你就可以得到像

项目

  list.get(1)获得(0); //第二个维度列表 - >整

编辑:

虽然这是事实,你可以使用地图,如果你要使用数字索引,例如每个列表,像这样:

 地图<整数,列表与LT; YourObject>>地图=新的HashMap<整数,列表与LT; YourObject>>();
map.put(0,新的ArrayList&所述; YourObject>());
map.put(5,新的ArrayList&所述; YourObject>());
map.get(0)。新增(新YourObject(你好));
map.get(5)。新增(新YourObject(世界));为(整数整数:map.keySet())
{
    对于(YourObject yourObject:map.get(整数))
    {
         yourObject.print(); //实例方法
         的System.out.println();
    }
}

虽然即使在当时列出的访问将是和以前一样,

  map.get(0)获得(1); //列表 - >在指标值

显然,你不需要使用整数作为泛型类型参数,这只是一个占位符类型。

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 dimentional array, if i want to access value then it can be as m[i][j].

But in arraylist how can i do that ?

解决方案

List<List<Integer>> list = new ArrayList<List<Integer>>();
list.add(new ArrayList<Integer>());
list.add(new ArrayList<Integer>());
list.get(0).add(5);
list.get(1).add(6);

for(List<Integer> 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<Integer, List<YourObject>> map = new HashMap<Integer, List<YourObject>>();
map.put(0, new ArrayList<YourObject>());
map.put(5, new ArrayList<YourObject>());
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.

这篇关于如何使作为Java的2维数组ArrayList的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆