Given an ArrayList write a Java method that returns a new Ar

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!

}

Solution

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]

*/

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.Arr
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.Arr

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site