Reputation: 37
In my code I have one vairable:
public Edge[] adjacencies;
now for initialization array is something like this:
v0.adjacencies = new Edge[] {
new Edge(v1, distance[0][1]),
new Edge(v2, distance[0][2]),
new Edge(v3, distance[0][3]),
new Edge(v4, distance[0][4]),
new Edge(v5, distance[0][5]),
new Edge(v6, distance[0][6]),
new Edge(v7, distance[0][7])
};
but I want to give dynamic initialization something like this:
v0.adjacencies = new Edge[] {
for(int i=1;i<8;i++)
new Edge("v"+i, distance[0][i]);
};
Upvotes: 1
Views: 1622
Reputation: 79875
Forget all about your variables v1
, v2
and so on. Just keep them all in an array to start with.
Vertex[] vertices = new Vertex[8];
for (int i = 0; i < 8; i++) {
vertices[i] = new Vertex();
}
vertices[0].adjacencies = new Edge[7];
for (int i = 1; i < 8; i++) {
vertices[0].adjacencies[i - 1] = new Edge(vertices[i], distance[0][i]);
}
Upvotes: 0
Reputation: 1193
You will want to look into the java.util package,
specifically the ArrayList class
. It has methods such as .add() .remove() .indexof() .contains() .toArray(),
and more
Upvotes: 0
Reputation: 17268
Vertex[] vertices = {v1,v2,v3,v4,v5,v6,v7};
v0.adjacencies = new Edge[7];
for(int i=1;i<8;i++) {
v0.adjacencies[i-1] = new Edge(vertices[i-1], distance[0][i]);
}
Try this.
Update: I assume those v1, v2, ... are objects of class Vertex (whatever you call it) and update the code accordingly.
Upvotes: 0
Reputation: 52185
How about something like this:
v0.adjacencies = new Edge[7];
for(int i = 1; 1 < 8; i++)
{
v0.adjacencies[i - 1] = new Edge("v"+i, distance[0][i]);
}
I'm assuming that v1
, v2
, etc are strings of the form v1
, v2
, etc.
Upvotes: 0
Reputation: 258
One way to do this dynamically is to create the array with the variable length.
length = 8;
v0.adjecencies = new Edge[length];
for(int i=1;i<length;i++)
v0.adjecencies[i-1] = new Edge("v"+i, distance[0][i]);
Upvotes: 1