I have a problem that is pretty basic but I am struggling to get right. Basically, I have a constructor that has some methods defined on it using this.
. I want to pass one of those methods a paramter, but I am struggling to declare it in a way that doesn't cause an error. This is my code:
public class Graph {
public Graph(int[][] gA) {
boolean[] visited = new boolean[gA.length];
Arrays.fill(visited, 0, gA.length, false);
//this is the bit I'm struggling with:
this.adj(int v) = gA[v];
this.array = gA;
this.visited = visited;
}
}
How do I get this.adj
to accept a parameter? I also tried creating a method declaration but couldn't get this work either. Is there some kind of design pattern I should use?
Thanks
EDIT: Apologies - made a mistake in the code excerpt. this.adj[v]
should be returning a row of the gA
array, which it only has access to within the constructor, so I cannot move the function outside.
This :
this.adj(int v) = adj(v);
Is the wrong way. Just use:
adj(v); // Call the method adj with the parameter v
Since you are calling it in the constructor, hence it does not matter if the method is static
or not. A constructor can call both of them.
Edit:
I want adj[v] to return the row of gA at v. I've edited the code above
You can do:
gA[v] = adj(v);
why you dont just call the method you defined??
public class Graph {
private YOUR_TYPE adj;
public Graph(int[][] gA) {
boolean[] visited = new boolean[gA.length];
Arrays.fill(visited, 0, gA.length, false);
//this is the bit I'm struggling with:
this.adj = adj(v);
this.array = gA;
this.visited = visited;
}
YOUR_TYPE adj(int v){
return .... something from YOUR_TYPE
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.