java - Preference when setting and adding an item at the some position in an arraylist -
i guess i'm asking difference between order of these 2 operations on arraylist.
suppose have following arraylists
arraylist<string> list = new arraylist<string>(); arraylist<string> list2 = new arraylist<string>(); list.add("tom"); list.add("jerry"); list.add(1,"harry"); list.set(1,"klaus"); system.out.println(list); output
[tom, klaus, jerry] then same thing list2except switch last 2 statements
list2.add("tom"); list2.add("jerry"); list2.set(1,"harry"); list2.add(1,"klaus"); system.out.println(list2); output
[tom, klaus, harry] when value setat posiotionwhy list addan item @ position+1 when attempt add new item @ positionas in second list. shouldn't list2 be?
[tom, klaus] and shouldn't listhave
[tom, klaus]
its simple
add inserts new value @ given index
and
set replace value @ given index.
have @ output after each statement.
list.add("tom"); // tom list.add("jerry"); // tom, jerry list.add(1,"harry"); // tom, harry, jerry list.set(1,"klaus"); // tom, klaus, jerry list2.add("tom"); // tom list2.add("jerry"); // tom, jerry list2.set(1,"harry"); // tom, harry list2.add(1,"klaus"); // tom, klaus, harry i hope, got now.
Comments
Post a Comment