The original solution is fairly efficient, I'm having trouble coming up with a cleaner method that is as efficient. However there are much cleaner/easier to read solutions.
Regarding the comment "just use HashSet", HashSet would destroy the order.
Here's a very clean solution using LinkedHashSet.
public static void main(String[] args) { List animals = new ArrayList(); animals.add("Horse"); animals.add("Crocodile"); animals.add("Cat"); animals.add("Hamster"); animals.add("Cat"); animals.add("Cat"); animals.add("Crocodile"); animals.add("Mouse"); animals.add("Elk"); System.out.println(animals); animals = removeDoubles(animals); System.out.println(animals); }
public static List removeDoubles(T list) { if (list == null) return list;
return new ArrayList(new LinkedHashSet(list)); }
Note in your original example you were assuming the list that is passed to the removeDoubles method was being modified in the method, and you ignored the list being returned by the method. Those are some bad assumptions to make.
See the snippet
Regarding the comment "just use HashSet", HashSet would destroy the order.
Here's a very clean solution using LinkedHashSet.
public static void main(String[] args) {
List animals = new ArrayList();
animals.add("Horse");
animals.add("Crocodile");
animals.add("Cat");
animals.add("Hamster");
animals.add("Cat");
animals.add("Cat");
animals.add("Crocodile");
animals.add("Mouse");
animals.add("Elk");
System.out.println(animals);
animals = removeDoubles(animals);
System.out.println(animals);
}
public static List removeDoubles(T list) {
if (list == null)
return list;
return new ArrayList(new LinkedHashSet(list));
}
Note in your original example you were assuming the list that is passed to the removeDoubles method was being modified in the method, and you ignored the list being returned by the method. Those are some bad assumptions to make.