4

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
user656523
  • 3,171
  • 3
  • 22
  • 19
  • 1
    Please, clarify what you mean by "If YES, then a value should be set to that index, else a value should be added to that index location." Maybe, with an example – Vlad Feb 02 '12 at 15:08
  • @Vlad Sure. Initially at index 0, value =30, so arraylist = [30]. When value at index 0 changes to 50, I want the arraylist to be = [50].When I tried this out with the add method, the arraylist gave [30,50] i.e it did not override the existing value, but simply added a new value. Hope that makes some sense. – user656523 Feb 02 '12 at 15:12
  • Yep, that's clear now (I was doubting as this case seemed too simple). And I guess, @hvgotcodes has already shown you the right direction. – Vlad Feb 02 '12 at 15:23
  • To be honest..I still haven't gotten the answer to my question (Maybe my question wasn't clear enough). I am aware of the add and set methods, but unsure how to apply them specifically for my code. – user656523 Feb 02 '12 at 15:28
  • Check my answer. Hope it helps. And hvgotcodes's answer has appropriate documentation links. – Vlad Feb 02 '12 at 15:56
  • I still don't see why you won't use a `Map` – stryba Feb 02 '12 at 17:06

7 Answers7

12

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]

girish TS
  • 209
  • 1
  • 3
  • 10
7

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.

Gaurav Sachdeva
  • 652
  • 1
  • 10
  • 23
5

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)

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
  • 1
    I dont think the add method will override/replace the existing element value at the specified index.When I tried out my code with add, this is what I got: Initially at index 0, value =30, so arraylist = [30]. When value at index 0 changes to 50, arraylist = [30,50].Thats the problem. – user656523 Feb 02 '12 at 15:11
  • read the documentation. Add does not replace. It inserts at the index and shifts everything to the right. Then look at the `remove` method, which is the next definition in the documentation. Or look at the `set` method – hvgotcodes Feb 02 '12 at 15:14
  • Exactly what I meant in my previous comment. :) It does not replace the existing value. How can I dynamically determine if I need to use an add method (if no value exists at the index location), or to use a set method (if value exists at the index location and needs replacing) ? – user656523 Feb 02 '12 at 15:21
4

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.

Vlad
  • 1,723
  • 12
  • 16
2

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?

stryba
  • 1,979
  • 13
  • 19
1

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.

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
user3400306
  • 111
  • 1
  • 4
  • @Dukeling ok. i have a arraylist of files. how can i know a specific file is in the arraylist. how to know this using contains method? Thanks – karimkhan Jun 29 '16 at 18:01
  • @karimkhan you pass the "specific file" as a parameter in the contains method. example: `ArrayList files = new ArrayList<>(); //this is your list` `files.add(new File("c:/path/file1.ext")); //populate the list with some random files` `files.add(new File("c:/path/file2.ext"));` `File myFile = new File("c:/path/file1.ext") //this is the file we are interested to find;` `boolean containsMyFile = files.contains(myFile); //test whether the list contains that file` `System.out.println(containsMyFile); //prints out "true". (sorry, not sure how to better format text in comments) – user3400306 Jan 07 '21 at 15:26
1

ArrayList.set(index, element) will add the specified element in the list at mentioned index. This will be replace operation so list size will remain unchanged. ArrayList.add(index, element) will add the specified element in the list at mentioned index. This is not replace operation so it will first right shift all elements from the mentioned index & finally will add the element at index position. Now size = size+1.

vickey123
  • 13
  • 5