Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Given an ArrayList, write a Java method that returns a new ArrayList which conta

ID: 3784214 • Letter: G

Question

Given an ArrayList, write a Java method that returns a new ArrayList which

contains only the non-duplicate elements from the original list.

import java.util.ArrayList;

public class Exercise1 {

public static void main(String[] args) {

ArrayList<Integer> list = new ArrayList<Integer>();

list.add(14);

list.add(24);

list.add(14);

list.add(42);

list.add(25);

ArrayList<Integer> newList = removeDuplicates(list);

System.out.print(newList);

}

public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list) {

// Your code here!

}

Explanation / Answer

HI, Please find my implementation.

Please let me know in case of any issue.

import java.util.ArrayList;

public class Exercise1 {

   public static void main(String[] args) {

       ArrayList<Integer> list = new ArrayList<Integer>();

       list.add(14);

       list.add(24);

       list.add(14);

       list.add(42);

       list.add(25);

       ArrayList<Integer> newList = removeDuplicates(list);

       System.out.print(newList);

   }

   public static <E> ArrayList<E> removeDuplicates(ArrayList<E> list) {

      

       ArrayList<E> noDupList = new ArrayList<>();

       // iterating over list

       for(E e : list){

           if(! noDupList.contains(e)) // if 'e' is not in noDupList then add it

               noDupList.add(e);

       }

      

       return noDupList;

   }

}

/*

Sample run:

[14, 24, 42, 25]

*/

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote