Suppose that I am collecting n amount of Strings into an array, or an array list, or some other data structure. I want to come up with a design that will allow the user to specify how the Strings will be sorted:
-If the user specifies option A, then the Strings will be put into a Vector, and then sorted and printed.
-If the user specifies option B, then the Strings will be put into a List, and then sorted and printed.
I want my design flexible enough to allow me to easily add additional sorting methods in the future (and my sorting methods).
My current implementation involves collecting the Strings from the user into an ArrayList, and then depending on the specified sorting method, I will use Collections.copy(array, vector) or Collections.copy(array, list). Then, I will do Collections.sort(vector or list).
(Currently, I am receiving NullPointerExceptions on Collections.copy)…
I am unsure of whether I am going about it in the best, most re-usable way. Any thoughts?
Thanks!
You need to use the interfaces that Java provides. When you take in an ArrayList you are forcing an implementation upon the user. Take in a
Collection<String>and they can use whatever they want.If you wanted to force them in to a List implementation you would simply specify
List<String>as the parameter. Then they can use a Vector, ArrayList, LinkedList, etc.In order to achieve the sorting you will simply want to pass in a Comparator and call
Collections.sort(myList, myComparator);So you would end up with something like …