如何在Java中将“ ArrayList”对象转换为“ String [] []”数组? 我需要一个二维String数组,而不是一个简单的Array
我有这个文件
word1 word1.1 word1.2
word2 word2.1 word2.2
我需要每个单词都可以与另一个文件进行比较
我尝试过
public void Scanne(File file) throws Exception {
Scanner scanner = new Scanner(file);
ArrayList<String> list = new ArrayList<String>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] parts = line.split("\t");
String part2 = parts[2];
String part3 = parts[3];
String part4 = parts[4];
String part5 = parts[5];
String part6 = parts[6];
String part7 = parts[7];
String part8 = parts[8];
String part9 = parts[9];
String part10 = parts[10];
list.add(line);
String resultSet[][]= new String[list.size()][parts.length];
for (int i = 0; i<list.size(); i++) {
I am stuck here
}
}
'''
答案 0 :(得分:0)
尝试此代码可能会对您有所帮助。
public class ArrayListToStringArray {
public static void main(String args[]){
//ArrayList containing string objects
ArrayList<String> nameList = new ArrayList<String>();
nameList.add("Max");
nameList.add("Tom");
nameList.add("John");
/*
* To convert ArrayList containing String elements to String array, use
* Object[] toArray() method of ArrayList class.
*
* Please note that toArray method returns Object array, not String array.
*/
//First Step: convert ArrayList to an Object array.
Object[] objNames = nameList.toArray();
//Second Step: convert Object array to String array
String[] strNames = Arrays.copyOf(objNames, objNames.length, String[].class);
System.out.println("ArrayList converted to String array");
//print elements of String array
for(int i=0; i < strNames.length; i++){
System.out.println(strNames[i]);
}
}
}
答案 1 :(得分:0)
根据OP的评论,要求按单词拆分,其中2d数组的每个单元格将存储一个单词,而每一行将对应一个句子。
List<String> l = new ArrayList<>();
l.add("Hello world");
l.add("StackOverflow is awesome");
String[][] s = new String[l.size()][];
for (int i=0; i<l.size(); i++) {
String[] words = l.get(i).split(" ");
s[i] = words;
}
for (int i=0; i<s.length; i++) {
for (int j=0; j<s[i].length; j++) {
System.out.print(s[i][j] + " ");
}
System.out.println();
}