Arraylist - Set/ add method usage - Java

后端 未结 7 1342
渐次进展
渐次进展 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:15

    You don't need to loop. ArrayList has an indexOf method you can use to get the first occurence of the object. Be sure to implement equals correctly.

    ArrayList also has an add method that allows you to set the index at which the element is inserted. Or a set method, that might be what you want (depending on exactly what you are trying to do)

    0 讨论(0)
  • 2021-01-14 06:28

    What you want is a Map rather than a List.

    What if counter is way bigger then List.size()? Do you add as many elements as needed in between?

    0 讨论(0)
  • 2021-01-14 06:31

    Here is the logic to determine where you need to insert or replace a value in your array.

    if (tempArray.indexOf(tempValue) < 0) {
        tempArray.add(counter, tempValue);
    } else {
        tempArray.set(counter, tempValue);
    }
    

    P.S. It's better to rename counter to index.

    0 讨论(0)
  • 2021-01-14 06:33

    ArrayList has the contains(Object o) method which "returns true if the list contains the specified element", likewise you can determine which method, add() or set() to use.

    0 讨论(0)
  • 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<String> al = new ArrayList<String>();
    
        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]

    0 讨论(0)
  • 2021-01-14 06:38

    The other answers already provide information about using indexOf methods available in the list. However, just to add some info about difference between "add" and "set" in the ArrayList in java.

    From the javadocs -

    add(index, value) method - Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

    set(index, value) - Replaces the element at the specified position in this list with the specified element.

    So using add() instead of set() increases your list size as well. You should consider this as well whether you need this behaviour or not.

    0 讨论(0)
提交回复
热议问题