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


Picture showing the message when user tries to enter data in Arraylist in Java
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Saturday, January 21, 2017

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250