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]
Answer from girish TS on Stack Overflowreplace - Arraylist - Set/ add method usage - Java - Stack Overflow
When to use Sets vs Lists .
How to set up an ArrayList object in java?
JAVA - Can't send update to ArrayList
I don't think this is ever going to return true:
enterPaymentConfirm == "y" || enterPaymentConfirm == "Y"
In Java you need to use equals() to compare strings, like this:
if (enterPaymentConfirm.equals("y") || enterPaymentConfirm.equals("Y")
What IDE are you using? Mine puts a red squiggly line under code if I try to compare two strings with == instead of equals because it's a common mistake.
More on reddit.comVideos
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]
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.
I acknowledge the difference between them on a basic level, like how sets don't allow duplicates and aren't in order, whereas lists have an order and allow duplicates, but from a performance standpoint, what are they better at doing? For example, if I have a group of integers that I want to store in no particular order, and contain no duplicates, will it always be better to store them in a set rathern than a list (with the exception of maybe a few very special cases)?