1

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]); 
 };
2
  • Sounds like v[i] needs to be an array, instead of v0, v1, v2 etc. Commented Oct 23, 2013 at 4:55
  • I certainly doubt if v* are strings, as assumed by everybody who has posted the answer. All those v1, v2.. seem to be some class(I guess Vertex) objects. Commented Oct 23, 2013 at 5:01

5 Answers 5

1

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]);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0
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.

3 Comments

java.lang.NullPointerException is coming
after that when I am calling from one function computePaths(v0); NullPointerException is coming
@user2908533 Updated. See if it fixes the issue.
0

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

Comments

0

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]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.