我有一个 Movie 对象,其中数据成员是 String 标题、int 年份和 ArrayList Actor 。我对如何添加这个ArrayList<String>
有点困惑到我的树。我正在从文件中读取此信息,例如:
Forrest Gump/1994/Tom Hanks
Star Wars/1977/Mark Hamill,Carrie Fisher,Harrison Ford
到目前为止,我已经能够添加除 ArrayList 之外的所有其他内容。我想我还需要line.split
数组的内容。另外,有些电影没有如示例中所示的多个 Actor ,所以我不确定如何实现这一点。我尝试了几种不同的方法,但最终得到了 IndexOutOfBoundsException
.
这是我到目前为止所拥有的:
try{
Scanner read = new Scanner( new File("movies.txt") );
do{
ArrayList<String> actorList = new ArrayList<String>();
String line = read.nextLine();
String [] tokens = line.split("/");
//I think I need to add another split for commas here.
//actorList.add() here
tree.add( new Movie(tokens[0], Integer.parseInt(tokens[1]), actorList ));
}while( read.hasNext() );
read.close();
}catch( FileNotFoundException fnf ){
System.out.println("File not found.");
}
如果需要的话,她是我的构造函数:
public Movie( String t, int y, ArrayList<String> a ){
title = t;
year = y;
actors = a;
}
最佳答案
希望下面的代码能够工作。拆分逗号分隔的 Actor 列表,将该 String
数组转换为 List
并将此 List
添加到您的 ArrayList
中。使用Arrays.asList()
作为一个简洁的实现。
try{
Scanner read = new Scanner( new File("movies.txt") );
do{
ArrayList<String> actorList = new ArrayList<String>();
String line = read.nextLine();
String [] tokens = line.split("/");
actorList.addAll(Arrays.asList(tokens[2].split(",")));
tree.add( new Movie(tokens[0], Integer.parseInt(tokens[1]), actorList ));
}while( read.hasNext() );
read.close();
}catch( FileNotFoundException fnf ){
System.out.println("File not found.");
}
关于java - 如何将逗号分隔的 ArrayList 添加到树中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30068559/