Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
650 views
in Technique[技术] by (71.8m points)

replace - Arraylist - Set/ add method usage - Java

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 index (using set method), else a value should be added to that index location(using add method)

Finding it a bit difficult to handle the above condition in my java code.Please help.

Here's what I have so far:

    ArrayList<Integer> tempArray = new ArrayList<Integer>();
        int counter = 0;
        int tempValue = 0;
    For LOOP -
      if (//certain conditions are satisfied){

      tempValue = calculateNewValue();
      tempArray.add(counter, tempValue); //Need some logic here to determine if its a set or add method to be used
    }
if (//some other conditions are satisfied){
       counter++;
}
    end For LOOP
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...