Write a Java program to search an element in a array list
- The import java.util.*; statement at the beginning of the code imports the java.util package, which provides various utility classes for working with collections, among other things.
- The public class Search_Element statement begins the definition of a new Java class called Search_Element. The public keyword indicates that this class can be accessed from other classes in the same package or from other packages, if necessary.
- The public static void main(String[] args) method is the entry point of the program. This is where the execution of the code begins. The String[] args parameter is used to pass any command-line arguments to the program (although in this case, no command-line arguments are being used).
- Inside the main method, a new ArrayList of strings called list_Col is created using the List interface. The List interface provides a way to work with ordered collections of elements.
- Several string elements are added to list_Col using the add method.
- The contains method of the List interface is used to check whether the string "Orange" is present in list_Col. If it is, the program prints "Found the element". If it is not, the program prints "There is no such element".
- Note that the if statement could also be written in a more concise form using the ternary operator, like this: System.out.println(list_Col.contains("Orange") ? "Found the element" : "There is no such element");.
Source Code
import java.util.*;
public class Search_Element
{
public static void main(String[] args)
{
List<String> list_Col = new ArrayList<String>();
list_Col.add("Red");
list_Col.add("Green");
list_Col.add("Orange");
list_Col.add("White");
list_Col.add("Black");
if (list_Col.contains("Orange"))
{
System.out.println("Found the element");
}
else
{
System.out.println("There is no such element");
}
}
}
Output
Found the element