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


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

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250