我是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?
答案 0 :(得分:0)
如果您希望其他班级有权访问aChars,您可以添加一个setter。如果您需要其他类可以访问aChars,则应将其添加到构造函数中。
需要列表
Class MyClass {
private List<Character> mChars;
// note how you cannot construct MyClass without providing the array
public MyClass( List<Character> chars ) {
mChars = chars;
if ( mChars == null ) {
throw new IllegalStateException("chars cannot be null");
}
}
private void doStuff() {
// now you can safely use the array is available (though maybe empty)
for( Character c : mChars ) {
System.out.println(c);
}
}
}
不需要列表
Class MyClass {
private List<Character> mChars;
// note how the constructor does not require the array
public MyClass() {
}
public void setChars( List<Character> chars ) {
mChars = chars;
}
// notice we had to do a null check
private void doStuff() {
if ( mChars != null ) {
// now you can safely use the array is available (though maybe empty)
for( Character c : mChars ) {
System.out.println(c);
}
}
}
}
请注意它们之间的区别在于是否需要使用该类。
答案 1 :(得分:0)
你问:
这是我的主要类,我应该如何初始化另一个类,以便我能够访问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;
}
然后在你的程序中你可以调用这个方法,在需要的时候传入文件。