Results 1 to 5 of 5
Thread: generic code
- 05-27-2010, 12:12 AM #1
generic code
I have these 2 methods working independently, basically doing the exact same thing to different data structures. Can you suggest a way to create a generic method instead of using 2?
Java Code:public String[] uniqueArguments(String[] arguments) { Set<String> noDups = new HashSet<String>(Arrays.asList(arguments)); return noDups.toArray(new String[noDups.size()]); }Java Code:public static ArrayList<String> uniqueArguments(List<String> u) { HashSet<String> mySet = new HashSet<String>(u); return new ArrayList<String>(mySet); }
- 05-27-2010, 12:48 AM #2
Senior Member
- Join Date
- Mar 2010
- Posts
- 266
- Rep Power
- 4
err... nope, cant do that
- 05-27-2010, 06:33 AM #3
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
Looking at the way you workout it's not possible. One reason I've seen is that the difference between those interfaces.
- 05-27-2010, 08:34 AM #4
Senior Member
- Join Date
- Aug 2009
- Posts
- 2,388
- Rep Power
- 6
Arrays don't play well generics.
The best you can do is
But it's not as bad as you think. If you have an array you can still use the method after calling the Arrays.asList method on it e.gJava Code:public static <T> List<T> uniqueList(Collection<T> collection) { Set<T> mySet = new HashSet<T>(collection); return new ArrayList<T>(mySet); }
Java Code:String[] stringsArray = new String[] { "f", "g", "f" }; System.out.println(uniqueList(Arrays.asList(stringsArray)));
- 05-27-2010, 05:06 PM #5
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
Similar Threads
-
generic types
By jon80 in forum New To JavaReplies: 6Last Post: 06-12-2009, 10:29 PM -
Generic methods
By andre1011 in forum Advanced JavaReplies: 7Last Post: 02-25-2009, 02:17 PM -
A generic interface example
By Java Tip in forum java.langReplies: 0Last Post: 04-17-2008, 07:42 PM -
Generic array
By eva in forum New To JavaReplies: 3Last Post: 12-23-2007, 12:12 AM -
Generic Hashtables
By ShoeNinja in forum New To JavaReplies: 0Last Post: 12-04-2007, 10:43 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks