+ 1

ArrayList

I am getting the output as 1,3,4 for the below program instead of 2,3,4. Can someone please explain why it is being considered as the reference but not the value in Integer case ? import java.util.ArrayList; public class MyClass { public static void main(String[ ] args) { ArrayList<Integer> colors = new ArrayList<Integer>(); colors.add(1); colors.add(2); colors.add(3); colors.add(4); colors.remove(1); System.out.println(colors); } }

27th Aug 2019, 3:48 PM
Yathish DC
Yathish DC - avatar
3 ответов
+ 13
import java.util.ArrayList; public class MyClass { public static void main(String[ ] args) { ArrayList<Integer> colors = new ArrayList<Integer>(); colors.add(1); // index 0 colors.add(2); // index 1 colors.add(3); // index 2 colors.add(4); // index 3 colors.remove(1); // remove index no 1 (it mens 2) System.out.println(colors); } }
27th Aug 2019, 6:42 PM
Sumit Programmer😎😎
Sumit Programmer😎😎 - avatar
+ 6
The reason 1 isn't being deleted from the arraylist is because the .remove function will remove any element at a specific index, and because you're deleting the element at index 1, 2 gets deleted
27th Aug 2019, 4:02 PM
Faisal
Faisal - avatar
0
When U put the int value into 'remove' method it will always refer to Index. U can avoid that by cast value into Integer. Exmpl: colors.remove((Integer) 1)
22nd Jan 2020, 10:24 PM
Kamil