简体   繁体   中英

how to simplify a multi-layer "ArrayList"?

I want to define many variables of type ArrayList<ArrayList<ArrayList<ArrayList<Integer>>>>

But that looks bad.

What I think of now is to create a class like the following

Public class ArrayListMulti{
    ArrayList<ArrayList<ArrayList<ArrayList<Integer>>>> ret;
    public void ArrayListMulti(){
        ret = new ArrayList<>();
    }
    public ArrayList<ArrayList<ArrayList<ArrayList<Integer>>>> getTheArrayList(){
        return ret;
    }
}

But using this method, every time I want to access the ret value, I must call the getTheArrayList method.

Is there an easier way?

Thanks in advance ~

You can extend ArrayList

public class ArrayListMulti extends ArrayList<ArrayList<ArrayList<ArrayList<Integer>>>>{}

Do you really need to have so deep array list? If so, you should thing about providing convenient API of your ArrayListMulti class. For instance, you can add methods like these:

public List<List<List<Integer>>> get(int i) {
    return ret.get(i);
}

public List<List<Integer>> get(int i, int j) {
    return ret.get(i).get(j);
}

...

and so on. (Don't forget to check nested lists for null.)

And one small tip: use a interface, not class when you define a class field (in your case List<List<List<List>>>> ret . It will make your code more robust if you want to change implementation of List interface (eg replace ArrayList to LinkedList ).

use multidimensional array like 3D array or more

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