java - List.remove removes odd elements -


it might obvious not able rationalise output of snippet. reference: this

public class sample {      public static void main(string[] args) {         set<integer> set = new treeset<integer>();         list<integer> list = new arraylist<integer>();          (int = -3; < 3; i++) {             set.add(i);             list.add(i);         }         system.out.println("after adding elements:");         system.out.println(set + " " + list);          (int = 0; < 3; i++) {             set.remove(i);             list.remove(i);         }         system.out.println("after removing elements:");         system.out.println(set + " " + list);     } } 

output:

after adding elements:

[-3, -2, -1, 0, 1, 2] [-3, -2, -1, 0, 1, 2]

after removing elements:

[-3, -2, -1] [-2, 0, 2]

i expecting:

after removing elements:

[-3, -2, -1] [0, 1, 2]

i.e. list.remove(i) should remove 1st ,2nd , 3rd item in list. fair enough ?

you change position of elements in list when remove first, code's behavior makes sense:

e.g.

for (int = -3; < 3; i++) {     set.add(i);     list.add(i); } system.out.println("after adding elements:"); system.out.println(set + " " + list);  (int = 0; < 3; i++) {     set.remove(i);     list.remove(i); } 

every time call list.remove(i), list smaller 1 item, , item position shifts left: item in position 1 goes position 0 , 1 in position 2 goes in position 1, etc...

use iterator remove elements or list's clear method.

if want remove integer object based on it's value, change int integer:

list.remove(integer.valueof(i)); 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -