Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to operate on an ArrayList of ArrayList in Java?

Tags:

java

arraylist

I'm facing a problem when operating on an ArrayList of ArrayList in Java. I have this thing in my code-

ArrayList<ArrayList<Integer>> L1 = new ArrayList<ArrayList<Integer>>();

Problem is, I have no idea as to how I should operate on this (addition, removal, traversal etc.). I wish to create an adjacency list (for implementing simple, undirected graphs), and my instructor suggests that I should create an ArrayList of ArrayList. I know I can do the following to add new element-

L1.add(//Something I want to add);

But this throws up an error in the current case for obvious reasons.

like image 370
Tarun Verma Avatar asked Jul 07 '26 10:07

Tarun Verma


2 Answers

An ArrayList of an ArrayList, just think that the outer object is an ArrayList and you are done.

ArrayList<ArrayList<Integer>> list2d = new ArrayList<ArrayList<Integer>>();
// add an element to the list
list2d.add(new ArrayList<Integer>());
// retrieve a list 
ArrayList<Integer> list1d = list2d.get(0);
// add an integer
list2d.get(0).add(123);

By the way, an adjacency list is just a list of edges, there's no need to store them for each vertex, especially if the graph is undirected. A list of Edge would be enough:

class Edge {
  Vertex v1, v2;
}

ArrayList<Edge> adjacencyList;

If you want to store them on a per vertex basis then you could avoid using a list of lists by encapsulating the edges inside the vertex class itself but this will require twice the edges:

class Vertex {
  int value;
  ArrayList<Vertex> adjacency;
}

but which one is best depends on what kind of operation you need to perform on the graph. For a small graph there is no practical difference.

Another possible implementation, if you just need to know if two vertex are connected:

class Edge {
  public final int v1, v2;

  public boolean equals(Object o) { return o != null && o instanceof Edge && o.hashCode() == hashCode(); }

  public int hashCode() { return v1 ^ v2; } // simple hash code, could be more sophisticated
}

Set<Edge> adjacencyList = new HashSet<Edge>();
like image 176
Jack Avatar answered Jul 15 '26 00:07

Jack


Try L1.get(i).add(whatever);, and of course first check whether L1.get(i) exists, otherwise add that inner list first.

It's something like this:

List<List<Integer>> L1 = new ArrayList<List<Integer>>(); //better use interfaces

List<Integer> first = null;
if( L1.size() > 0) {
 first = L1.get(0); //first element
}
else {
  first = new ArrayList<Integer>();
  L1.add(first);      
}

first.add(4711); //or whatever you like to add
like image 44
Thomas Avatar answered Jul 15 '26 00:07

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!