From 3abd0f634e26f0ebed0794f0d183af37be8df19d Mon Sep 17 00:00:00 2001 From: Sleek Panther Date: Sat, 8 Jul 2017 16:17:31 -0400 Subject: [PATCH] Fixed Exercise 19_03 (Actually removes duplicates & returns new list) --- .../Exercise_19_03/Exercise_19_03.java | 39 +++++++++++-------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/Exercise_19/Exercise_19_03/Exercise_19_03.java b/Exercise_19/Exercise_19_03/Exercise_19_03.java index 56570ea0..ab8ecbaf 100644 --- a/Exercise_19/Exercise_19_03/Exercise_19_03.java +++ b/Exercise_19/Exercise_19_03/Exercise_19_03.java @@ -1,22 +1,29 @@ -/********************************************************************************* -* (Distinct elements in ArrayList) Write the following method that returns a new * -* ArrayList. The new list contains the non-duplicate elements from the original * -* list. * -* * -* public static ArrayList removeDuplicates(ArrayList list) * -*********************************************************************************/ +/************************************************************************************** +* (Distinct elements in ArrayList) Write the following method that returns a new * +* ArrayList. The new list contains the non-duplicate elements from the original list. * +* * +* public static ArrayList removeDuplicates(ArrayList list) * +**************************************************************************************/ import java.util.ArrayList; public class Exercise_19_03 { /** Removes duplicate elements from an array list */ - public static > - ArrayList removeDuplicates(ArrayList list) { - for (int i = 0; i < list.size() - 1; i++) { - for (int j = i + 1; j < list.size(); j++) { - if (list.get(i).compareTo(list.get(j)) == 0) - list.remove(j); + public static > ArrayList removeDuplicates(ArrayList list) { + ArrayList newList = new ArrayList(); + if(!list.isEmpty()){ + newList.add(list.get(0)); //adds 1st item from reference list + for (int i = 1; i < list.size(); i++) { //loop starts from 1 + boolean shouldAddToNewList = true; + for (int j = 0; j < newList.size(); j++) { + if (list.get(i).compareTo(newList.get(j)) == 0){ + shouldAddToNewList = false; + } + } + if(shouldAddToNewList){ + newList.add(list.get(i)); + } } } - return list; - } -} \ No newline at end of file + return newList; + } +}