开发者

Java Collections & aliasing

开发者_JAVA技巧

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜