我需要用一种方法创建一个空列表并保存引用。然后,我需要将引用传递给另一个方法,其中列表中填充有形状及其参数。
公开课测试{
public static void start() { ArrayList<Object> shapes = new ArrayList<>(); } public static void create() { BufferedReader file = new BufferedReader(new FileReader("dataFile.txt")); if (file.readLine() == "Rectangle") { String shapeType = file.readLine(); String name = file.readLine(); Double length = Double.valueOf(file.readLine()); Double width = Double.valueOf(file.readLine()); Rectangle newShape = new Shape.Rectangle(name, length, width); shapes.add(newShape); // this is where this class cannot recognize "shapes" list
你不能,不是那种设计。
start()
创建一个列表,将引用保存在其 shapes
局部变量中,然后..将该变量扔进垃圾箱。该物体被制造出来并立即变成垃圾。
您可以返回该列表,然后将其传递给创建:
public static List<Shape> start() {
return new ArrayList<Shape>();
}
public static void create(List<Shape> shapes) {
...
}
或更可能的是,
static
不是您应该使用的东西。一般来说,如果有人在学习java并开始到处撒static
,那就不会顺利。你不应该使用它......一年。是的,main
必须如此,所以,让你的main
方法成为一个单行:new MainClass().go()
- 现在你已经“脱离”了static
并且可以完全停止使用它。
因此:
public class ShapesProcessor {
private final List<Shape> shapes = new ArrayList<>();
public void create() {
... code here - shapes is available ...
}
}
请注意,我们在 java 中不使用“启动”方法,而是使用构造函数。上面的代码有一个隐式的;自动创建
new ShapesProcessor()
“开始”(创建列表并将其引用分配给字段)。