How do you deal with aliasing in Java? A simple solution is to make a copy of let's say an ArrayList but when i try to write the code my data keeps being overwritten by newly added data. In detail:
ArrayList<ArrayList> temp = new ArrayList<ArrayList>() ;
ArrayList<ArrayList> personRecord = new ArrayList<ArrayList>() ;
ArrayList<String> personDetail = new ArrayList<String>() ;
...
while (input.hasNextLine())
{
String line = input.nextLine() ;
String [] tokens = line.split(" ", 0) ;
for (String s: tokens )
{
personDetail.add(s) ;
}
temp.add(personDetail) ;
personRecord.addAll(temp) ;
temp.clear() ;
personDetail.clear() ;
}
output:
[[Peter, M, 1972], [Peter, M, 1972]]
instead of:
[[Peter, M, 1972], [Anne, F, 1974]]
You should move personDetail creation inside of the loop to get a new Arraylist for every person:
ArrayList<ArrayList> personRecord = new ArrayList<ArrayList<String>>() ;
while (input.hasNextLine())
{
ArrayList<String> = new ArrayList<String>();
String line = input.nextLine() ;
String [] tokens = line.split(" ", 0) ;
for (String s: tokens )
{
personDetail.add(s) ;
}
personRecord.add(personDetail);
}
temp
is not needed in any case.
Looks like you're used to C++ collections! Object references in Java are pointers (despite the reference syntax) and collections are collections of pointers. Collections never copy objects when they are added. If you want to make a list of lists, then allocate the list-of-lists outside the loop, and inside the loop, allocate a single list at the top of the loop. Fill it during the loop body, and add it to the list-of-lists at the bottom of the loop. That's it. No temporaries needed.
精彩评论