Articles → Java → How To Prevent Duplicate Element Insertion In Arraylist In Java
How To Prevent Duplicate Element Insertion In Arraylist In Java
Indexof Method
Syntax
arrayListObject.Index(“string”)
Example
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class MyClass {
public static void main(String[] args) throws java.lang.Exception {
ArrayList < String > list = new ArrayList < String > ();
list.add("Test");
if (list.indexOf("Test") > -1) {
System.out.println("Data already exists");
}
}
}
Output
Click to Enlarge