我觉得这很简单,因为我很确定我以前做过,但我似乎无法让它工作.我的班级是:
public class City
{
String start = null;
String end = null;
int weight = 0;
}
Run Code Online (Sandbox Code Playgroud)
我在做:
City cityGraph[] = new City[l];
Run Code Online (Sandbox Code Playgroud)
当我尝试访问cityGraph [x] .start时,我得到一个空指针异常,所以我想我也需要初始化数组中的每个元素,所以我这样做:
for(int j = 0; j < l; j++)
{
cityGraph[j] = new City();
}
Run Code Online (Sandbox Code Playgroud)
但它给了我这个错误:
No enclosing instance of type Graphs is accessible.
Must qualify the allocation with an enclosing instance
of type Graphs (e.g. x.new A() where x is an instance of Graphs).
Run Code Online (Sandbox Code Playgroud)
我不知道这意味着什么,或者如何解决它.任何帮助,将不胜感激!
当你声明public class City为public class Graphs类似的内部类时,就会发生这种情况
public class Graphs {
public class City {
}
}
Run Code Online (Sandbox Code Playgroud)
这样,在City不首先构造Graphs实例的情况下就无法构造.
您需要构建City如下:
cityGraph[j] = new Graphs().new City();
// or
cityGraph[j] = existingGraphsInstance.new City();
Run Code Online (Sandbox Code Playgroud)
这实在是没有意义.而是将其提取City到一个独立的类中,
public class Graphs {
}
Run Code Online (Sandbox Code Playgroud)
public class City {
}
Run Code Online (Sandbox Code Playgroud)
或通过声明它使其成为静态嵌套类static.
public class Graphs {
public static class City {
}
}
Run Code Online (Sandbox Code Playgroud)
无论哪种方式,你都可以City通过公正的方式构建一个新的new City().