Removed duplicates from list

shragi
shragi used Ask the Experts™
on
Hi I wrote the below code to remove the duplicates from the arraylist.

      public static ArrayList<Integer> noDuplicates(ArrayList<Integer> inputList)
          {      
                   HashSet<Integer> inputListToSet = new HashSet<Integer>(inputList);
                   ArrayList<Integer> inputListWithoutDuplicates = new ArrayList<Integer>(inputListToSet);
                   return inputListWithoutDuplicates;
          }      

But i want to change this program to work for other numeric classes and generic objects?
what should i change ?

Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Check out generic methods:
https://docs.oracle.com/javase/tutorial/extra/generics/methods.html

This will let you modify your code to something like this, where "T" stands for the generic type of the objects, so then this code will work with Integer or Double or whatever.

 public static <T> ArrayList<T> noDuplicates(ArrayList<T> inputList) ...

Doug

Author

Commented:
thanks dpearson :)
Top Expert 2016

Commented:
Bear in mind your code will likely reorder the List too unless you use a LinkedHashSet

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial