I am trying to read a text file into an ArrayList<ArrayList<String>>
The File Looks like:
A D E F
B A F
C A B D
D B C
E B C D F
F A B D
G
H A D F
Following is my piece of code:
private static void registerPages() throws IOException {
Scanner input = new Scanner(new File(webPath));
//input.useDelimiter(" ");
ArrayList<ArrayList<String>> arrayList = new ArrayList<>();
ArrayList<String> row = new ArrayList<>();
String tempStr;
String[] tempArr;
while (input.hasNextLine())
{
row.clear();
tempStr = input.nextLine(); //get row in string
tempArr = tempStr.split(" "); //split string into strings[]
Collections.addAll(row, tempArr); //add each strings[] to arrayList
arrayList.add(row); //add arrayList to arrayList
}
System.out.println("arrayList:\n" + arrayList);
}
The output is:
arrayList:
[[H, A, D, F], [H, A, D, F], [H, A, D, F], [H, A, D, F], [H, A, D, F], [H, A, D, F], [H, A, D, F], [H, A, D, F]]
The wanted output is:
arrayList:
[[A, D, E, F], [B, A, F], [C, A, B, D], [D, B, C], [E, B, C, D, F], [F, A, B, D], [G], [H, A, D, F]]
Just FYI, this text file is supposed to be a webgraph. First word is a web-page. Next words in the same line are other webpages linking to this web-page (in-links). Eventually, i am supposed to code the 'Page Rank' algorithm.
Thank You in advance.
Instead of using row.clear()
try instantiate row in each iterations.
row = new ArrayList<>()
Hint:
You are creating row
only once. So all item holders in arrayList points to the same memory block. You have to create new instances (Real object in memory) so they can hold different values.