import java.util.*; // for ArrayList public class Ch21_3 // this program will create several different types of ArrayLists which can contain duplicate elements. It will use a generic method that will remove { // duplicates from the array list. It will be Generic in that it can handle any type of element for the ArrayList. public static void main(String[] args) { ArrayList a=new ArrayList<>(); // create three different ArrayLists and populate them with values, some duplicated ArrayList b=new ArrayList<>(); ArrayList c=new ArrayList<>(); a.add("Frank");a.add("Jimi");a.add("Jimmy");a.add("Steve");a.add("Jimmy");a.add("Steve");a.add("Mike");a.add("Frank"); b.add(new Integer(5));b.add(new Integer(15));b.add(new Integer(2));b.add(new Integer(15));b.add(new Integer(25));b.add(new Integer(3));b.add(new Integer(15));b.add(new Integer(25)); c.add(new Double(1.2));c.add(new Double(2.3));c.add(new Double(3.4));c.add(new Double(4.5));c.add(new Double(5.6));c.add(new Double(6.7));c.add(new Double(3.4));c.add(new Double(3.5)); a=removeDuplicates(a); // removeDuplicates returns a new ArrayList of the same type which has no duplicates, reassign the variables to the returned ArrayList b=removeDuplicates(b); c=removeDuplicates(c); System.out.println(a); // print out new version of the ArrayList System.out.println(b); System.out.println(c); } // receive an ArrayList of Generic type E, create an empty ArrayList of type E, add each element of list to the new list (list2) as long as it doesn't already exist in list2 public static ArrayList removeDuplicates(ArrayList list) { ArrayList list2=new ArrayList<>(); for(E item:list) // iterate for each element in the original list if(!list2.contains(item)) list2.add(item); // if this item is not in the new list, add it return list2; // and return the new list which will not have any duplicates } }