本文介绍了访问ArrayList< ArrayList< SomeObject>>分子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ArrayList ArrayList ,我需要找到一种访问元素的简单方法,让我更容易理解我已经实现了我想要实现的目标:

I have an ArrayList of ArrayLists where i need to find a simple way of accessing the elements, to make it easier to understand i have drawn my goal of what i want to achieve:

如上图所示,主 ArrayList 包含 m ArrayList ,其中我希望使用 get 方法获取元素从0到 N 元素,其中 N ArrayList1 ArrayList2的总元素。可能会出现更多的ArrayList。

As seen on the image above the main ArrayList consists of m ArrayList, where i wish to get an element by using a get method which goes from 0 to N elements, where N is the total elements of ArrayList1 and ArrayList2. More ArrayList's may occur.

我当然可以通过使用两个for循环遍历元素,这不是我在这种情况下搜索的内容。

I can of course iterate through the elements by using two for-loops, which is not what im searching for in this case.

推荐答案

您需要在新的包装器类上基本拥有 ArrayList 成员以不同的方式实现它们。我掀起了一个示例,演示了在 get()中计算的正确索引。

You would need to basically have the the ArrayList members on your new wrapper class and implement them in a different manner. I whipped up an example that demonstrates the correct index being calculated in get().

import java.util.ArrayList;

public class ListHolder<T> {
    public ArrayList<ArrayList<T>> list = new ArrayList<ArrayList<T>>();

    public int size() {
        int size = 0;
        for (int i = 0; i < list.size(); i++) {
            size += list.get(i).size();
        }
        return size;
    }

    public T get(int i) {
        if (i >= size())
            return null;

        int listIndex = 0;
        int valueIndex = i;

        while (valueIndex >= list.get(listIndex).size()) {
            valueIndex -= list.get(listIndex++).size();
        }

        return list.get(listIndex).get(valueIndex);
    }
}

我用来验证我的方法:

public static void main(String[] args)
{
    ListHolder<Object> listHolder = new ListHolder<Object>();

    listHolder.list.add(new ArrayList<Object>());
    listHolder.list.get(0).add("hello");
    listHolder.list.get(0).add("world");

    listHolder.list.add(new ArrayList<Object>());
    listHolder.list.get(1).add("a");
    listHolder.list.get(1).add("b");
    listHolder.list.get(1).add("c");

    System.out.println("Size: " + listHolder.size());
    System.out.println("listHolder[0]: " + listHolder.get(0)); // "hello"
    System.out.println("listHolder[1]: " + listHolder.get(1)); // "world"
    System.out.println("listHolder[2]: " + listHolder.get(2)); // "a"
    System.out.println("listHolder[3]: " + listHolder.get(3)); // "b"
    System.out.println("listHolder[4]: " + listHolder.get(4)); // "c"
    System.out.println("listHolder[5]: " + listHolder.get(5)); // "null"
}

这篇关于访问ArrayList&lt; ArrayList&lt; SomeObject&gt;&gt;分子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 05:22