java - How do I add a null object to an ArrayList inside an ArrayList -
i trying represent ad hoc network using adjacency matrix structure. this, creating arraylist inside arraylist.
when add new vertex graph, create new arraylist (inside super arraylist) , have loop add new null object each arraylist, size of arraylists not increase correctly , can't figure out why.
here code:
public class matrix { public arraylist<arraylist<edge>> graph; public arraylist<vertex> verticies; public arraylist<edge> edges; public matrix() { graph = new arraylist(); verticies = new arraylist(); edges = new arraylist(); } public matrix(arraylist<vertex> verticies, arraylist<edge> edges) { this.verticies = verticies; this.edges = edges; } public void addvertex(vertex v) { verticies.add(v); graph.add(new arraylist()); for(int i=0; i<graph.size()-1; i++ ) { graph.get(i).add(null); } }
any appreciated.
the initial size of graph
0
, for
loop in addvertex()
runs 1 time less should:
public void addvertex(vertex v) { verticies.add(v); graph.add(new arraylist()); // graph has size 1 (int = 0; < graph.size() - 1; i++) { // = 0, 0 < 0 false graph.get(i).add(null); // not executed last added list } }
the next time call addvertex()
add null
previous arraylist
s, not 1 added.
so should do:
for (int = 0; < graph.size(); i++)
even fix though, note if call addvertex()
5 times have this:
index arraylist 0 [null, null, null, null, null] 1 [null, null, null, null] 2 [null, null, null] 3 [null, null] 4 [null]
this not want. better approach add vertices first:
public void addvertex(vertex v) { this.vertices.add(v); }
and create arraylist
s adjacency matrix appropriate size:
public void initializeadjacencymatrix() { int n = this.vertices.size(); (int = 0; < n; i++) { list<edge> edges = new arraylist<>(collections.ncopies(n, null)); graph.add(edges); } }
also, you're using raw types when instantiating arraylist
s. not practice. should use diamond operator instead. example:
graph = new arraylist<>(); graph.add(new arraylist<>());