# Adjacency Matrix with an ArrayList of ArrayLists

Printable View

• 04-09-2013, 04:46 AM
clickhere9
Adjacency Matrix with an ArrayList of ArrayLists
Hi guys,

I am very new to Java and programming in general so please excuse any noob things I do/ask :P:

I am trying to create an Adjacency Matrix for a graph and decided to use an ArrayList of ArrayLists (is there a better way to represent a 2D array?)

Code:

`private ArrayList<ArrayList<int>> adjacencyMatrix;`
I've also got another ArrayList called listOfNodes which just contains all the nodes in the graphs. I use the index of the nodes in this list as the row & column indexes in the adjacencyMatrix.

Now, I'm writing a method to remove a node and I was just wondering if this will work:

Code:

```        public void removeNode (T a){                 //For every column                 for (int i = 0; i<listOfNodes.size(); i++){                                                 int index = listOfNodes.indexOf(a);                                                 if (adjacencyMatrix.get(i) != null){                                 adjacencyMatrix.get(i).get(index) = 0;                         } else {                                 //exit the moment we encounter a null column (means end of graph)                                 return;                         }                 }                 //Remove node 'a's column                 adjacencyMatrix.remove(index);                 //Remove node in the listOfNodes                 listofNodes.remove(index);         }```
• 04-09-2013, 04:57 AM
Junky
Re: Adjacency Matrix with an ArrayList of ArrayLists
Quote:

Originally Posted by clickhere9
Now, I'm writing a method to remove a node and I was just wondering if this will work:

Why ask us? You can easily test it yourself by compiling and running your code.
• 04-09-2013, 04:59 AM
clickhere9
Re: Adjacency Matrix with an ArrayList of ArrayLists
Oh hang on, I just realised why that wouldn't work. I changed this line:

Code:

`            adjacencyMatrix.get(i).get(index) = 0;`
to:

Code:

`        adjacencyMatrix.get(i).remove(index);`
Hopefully that should do it?