猿问

我正在尝试公开一个 ArrayList(在 Java 中),以便我可以在不同的类中访问它

有一个错误,我不确定在无法访问另一个类中的 ArrayList 的情况下我应该做什么


package LifeGame;

import java.util.ArrayList;

public class Lists {


    public static void main(String[] args) {

    public ArrayList<String> tasks = new ArrayList<String>(); { // error on `tasks`

        tasks.add("Phone");

    }


    }

}


神不在的星期二
浏览 175回答 3
3回答

尚方宝剑之说

方法内的变量只能从同一方法内通过名称访问。类成员——在方法之外定义的变量——是唯一可以是公共、私有等的成员。

万千封印

您必须在方法之外将其声明为类成员package LifeGame;import java.util.ArrayList;public class Lists{&nbsp; &nbsp;public static ArrayList<String> tasks;&nbsp; &nbsp; public static void main(String[] args)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; tasks =&nbsp; new ArrayList<String>();&nbsp; &nbsp; &nbsp; &nbsp; tasks.add("Phone");&nbsp; &nbsp;}}所以你可以在任何地方使用它。例如:import java.util.ArrayList;public class Lists {&nbsp; &nbsp; public static ArrayList<String> tasks;&nbsp; &nbsp; public Lists() {&nbsp; &nbsp; &nbsp; &nbsp; tasks = new ArrayList<String>();&nbsp; &nbsp; }&nbsp; &nbsp; public void addTask(String task) {&nbsp; &nbsp; &nbsp; &nbsp; tasks.add(task);&nbsp; &nbsp; }&nbsp; &nbsp; public ArrayList<String> getTasks(){&nbsp; &nbsp; &nbsp; &nbsp; return tasks;&nbsp; &nbsp; }&nbsp; &nbsp; public void printTasks() {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(tasks);&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; Lists l = new Lists();&nbsp; &nbsp; &nbsp; &nbsp; l.addTask("Phone");&nbsp; &nbsp; &nbsp; &nbsp; l.addTask("Clean");&nbsp; &nbsp; &nbsp; &nbsp; l.printTasks();&nbsp; &nbsp; }}希望这可以帮助。

鸿蒙传说

你的代码应该是:package LifeGame;import java.util.ArrayList;public class Lists {&nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp;ArrayList<String> tasks = new ArrayList<String>();&nbsp;&nbsp; &nbsp; &nbsp;tasks.add("Phone");&nbsp; &nbsp;&nbsp;&nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答