Arraylist - Set/ add method usage - Java

后端 未结 7 1405
渐次进展
渐次进展 2021-01-14 06:03

I have an Arraylist of integers. My requirement is to determine if the arraylist HAS an element existing at the specified index.If YES, then a value should be set to that in

7条回答
  •  日久生厌
    2021-01-14 06:34

    set method replaces the element in the specified position with the new element. But in add(position, element) will add the element in the specified position and shifts the existing elements to right side of the array .

    ArrayList al = new ArrayList();
    
        al.add("a");
        al.add(1, "b");
        System.out.println(al);
    
        al.set(0, "c");
        System.out.println(al);
    
        al.add(0, "d");
        System.out.println(al);
    

    ---------------Output -------------------------------------

    [a, b]

    [c, b]

    [d, c, b]

提交回复
热议问题