简体   繁体   中英

Is list.clear() working backwards too?

Some weird problem. I have a for loop which gets draw numbers from list and arranges them in pairs. I want a hashmap that would store paris and drawing number, so;

there's a list containing: 1,2,3,4,5,6,7,8 for loop starts here, 1: 1 and 2 2: 3 and 4 3: 5 and 6 4: 7 and 8

that's what I've created;

List<Integer> numbers = new List<Integer>;
HashMap<Integer, <List<Integer>> parimap = new HashMap<Integer,<List<Integer>>;

for(int i=0; i<4; i++){
        int firstinpair = numbers.get(0);
        int secondinpair = numbers.get(1);
        numbers.remove(0);                       //so it won't repeat
        numbers.remove(0);                      
        int pairnumber=i+1;
        temporary.add(0,firstinpair);
        temporary.add(0, secondinpair);
        pairmap.put(pairnumber, temporary);
}

And what I get is:

{1=[5, 2, 6, 4, 8, 3, 1, 7], 2=[5, 2, 6, 4, 8, 3, 1, 7], 3=[5, 2, 6, 4, 8, 3, 1, 7], 4=[5, 2, 6, 4, 8, 3, 1, 7]}

I've tried like this:

temporary.add(firstinpair);
temporary.add(secondinpair);
pairmap.put(pairnumber, temporary);
temporary.clear();

And then:

{1=[], 2=[], 3=[], 4=[]}

I have no idea what I am doing wrong. Please help!

Your problem is that you keep adding the same list object to your map within your loop. So all map keys point to the same value ( pairmap.put(pairnumber, temporary); is the culprit here).

Instead: create a new list temporary during each loop iteration; and then put that list into your map!

Besides: you might want to improve your naming . You see, temporary says nothing about the thing that this variable denotes. And then variable names should go camelCase, as firstInPair is kinda easier to read.

Finally: there is no point in removing the elements from that list - instead of always fetching the first two elements, you could simply do two calls using get(i) resp. i+1. It doesn't really matter in your small example, but for "real world" scenarios: removing the first element in an ArrayList is the most expensive operation that you can perform on such lists!

And as said; you absolutely do not need to do that. Your solution is more complicated (harder to read/understand) and more expensive at run time!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM