如何从包含长数组的arraylist中检索元素

vsikbqxv  于 2021-07-03  发布在  Java
关注(0)|答案(3)|浏览(265)

如何从中检索元素 ArrayList<long[]> ?
我这样写道:

ArrayList<long []>  dp=new ArrayList<>();

//m is no of rows in Arraylist
for(int i=0;i<m;i++){
    dp.add(new long[n]);   //n is length of each long array
    //so I created array of m row n column
}

现在如何得到每个元素?

iswrvxsc

iswrvxsc1#

列表中的每个元素都是一个数组。。。因此,您需要小心地添加它们:使用匿名数组 new long[] { 1L, 2L, 3L } 或者使用new关键字指定大小 new long[5] ```
public static void main(String[] args) throws Exception {
ArrayList<long[]> dp = new ArrayList<>();
// add 3 arrays
for (int i = 0; i < 3; i++) {
dp.add(new long[] { 1L, 2L, 3L });
}
// add a new array of size 5
dp.add(new long[5]); //all are by defaul 0
// get the info from array
for (long[] ls : dp) {
for (long l : ls) {
System.out.println("long:" + l);
}
System.out.println("next element in the list");
}
}

nsc4cvqm

nsc4cvqm2#

您还可以有一个包含long数组的object的arraylist。但到目前为止,代码的问题是没有在每个长数组中放入任何值。

public class NewClass {

    private static class MyObject {
        private long []v;

        public MyObject(int n) {
            v = new long[n];
        }

        @Override
        public String toString() {
            String x = "";

            for (int i = 0; i < v.length; i++) {
                x += v[i] + " ";
            }
            return x;
        }
    }

    public static void main(String[] args) {
        ArrayList<MyObject> dp = new ArrayList();
        int m = 3;
        int n = 5;

        for (int i = 0; i < m; i++) {
            dp.add(new MyObject(n));
        }

        for (MyObject ls : dp) {
            System.out.println(ls);
        }
    }
}
0ejtzxu1

0ejtzxu13#

你得到数组的方式和你从 ArrayList . 例如,要得到第十个 long[] 储存在 ArrayList ,你会用 get 方法:

long[] tenthArray = dp.get(9);

相关问题