我是Java的新手,所以我的问题很基本。我在一类中有一个数组列表,我需要将其传递给另一类。我怎样才能做到这一点?
这就是我初始化ArrayList-的方式
public class Main {
public static void main(String[] args) throws IOException {
File file = new File("C:\...");
List<Character> aChars = new ArrayList<Character>();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));
int c;
while((c = reader.read()) != -1) {
aChars.add((char) c);
}
}
}
这是我的主类,我应该如何初始化另一个类,以便能够访问arrayList achars?
你问:
这是我的主类,我应该如何初始化另一个类,以便能够访问arrayList achars?
首先,通过将大部分代码获取到main方法之外。相反,您将需要制作面向对象的兼容类,具有状态(实例字段)和行为(非静态方法)的类。
例如,您可以为您的类提供一个从文件中读取并返回感兴趣的ArrayList的方法:
public List<Character> getCharsFromFile(File file) {
List<Character> aChars = new ArrayList<Character>();
//.... code that reads form the file and places data into aChars
return aChars;
}
然后在程序中稍后可以调用此方法,并在需要时传入文件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句