Results 1 to 5 of 5
Thread: generic code
- 05-27-2010, 01: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, 01:48 AM #2
Senior Member
- Join Date
- Mar 2010
- Posts
- 266
- Rep Power
- 11
err... nope, cant do that
- 05-27-2010, 07:33 AM #3
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,370
- Blog Entries
- 1
- Rep Power
- 26
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, 09:34 AM #4
Senior Member
- Join Date
- Aug 2009
- Posts
- 2,388
- Rep Power
- 14
Arrays don't play well generics.
The best you can do is
Java 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, 06:06 PM #5
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,370
- Blog Entries
- 1
- Rep Power
- 26
Similar Threads
-
generic types
By jon80 in forum New To JavaReplies: 6Last Post: 06-12-2009, 11:29 PM -
Generic methods
By andre1011 in forum Advanced JavaReplies: 7Last Post: 02-25-2009, 03:17 PM -
A generic interface example
By Java Tip in forum java.langReplies: 0Last Post: 04-17-2008, 08:42 PM -
Generic array
By eva in forum New To JavaReplies: 3Last Post: 12-23-2007, 01:12 AM -
Generic Hashtables
By ShoeNinja in forum New To JavaReplies: 0Last Post: 12-04-2007, 11:43 PM
Bookmarks