package com.gea.boe.bean;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class BoeMain
{
public static void main(String[] args)
{
ArrayList<String> myList = new ArrayList<String>();
myList.add("item1");
myList.add("item2");
myList.add("item3");
myList.add("item4");
// Display
display(myList);
// Remove
addAndRemoveFromArrayList(myList, 1, "REMOVE");
// Display
display(myList);
// Add
addAndRemoveFromArrayList(myList, 1, "ADD");
// Display
display(myList);
// Sorting
sortingArrayList(myList);
// Display
display(myList);
//Searching
searchingFromArrayList(myList,"item4");
}
// Remove items from Array List
public static void addAndRemoveFromArrayList(ArrayList<String> arrayList, int indexOfItemToRemove, String addRemove)
{
if ("ADD".equalsIgnoreCase(addRemove))
{
String addItem = "item9";
arrayList.add(indexOfItemToRemove, addItem);
}
else if ("REMOVE".equalsIgnoreCase(addRemove))
{
arrayList.remove(indexOfItemToRemove);
}
}
// Here is the list, output methods
public static void display(ArrayList<String> arrayList)
{
System.out.println("There are (" + arrayList.size() + ") items in the list.");
// output method 1
for (int i = 0; i < arrayList.size(); i++)
{
System.out.println(i + " -->> " + arrayList.get(i));
}
// output method 2
for (Iterator<String> iter = arrayList.iterator(); iter.hasNext();)
{
System.out.println("-->> " + iter.next());
}
// output method 3
System.out.println(arrayList);
}
// Sorting Array List
public static void sortingArrayList(ArrayList<String> arrayList)
{
Collections.sort(arrayList);
}
//Searching
public static void searchingFromArrayList(ArrayList<String> arrayList,String searchItem)
{
boolean searchResult = arrayList.contains(searchItem);
if(searchResult == true)
System.out.println("Item found at position " + arrayList.indexOf(searchItem));
else
System.out.println("Item NOT found");
}
}
No comments:
Post a Comment