java different sorting methods on one set of data
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开发者_如何学C 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 ...
public List<String> sortThem(List<String> strings, Comparator<String> comp) {
... do cool things ...
Collections.sort(strings, comp);
return strings;
}
Java Collections copy list - I don't understand
have a look at that - it will explain the null pointer
Is this similar to what you're looking for?
import java.util.Collection;
public interface ISortable {
public Collection<String> sort(String[] strings);
}
And as an example implementing class:
import java.util.Collection;
import java.util.Vector;
public class StringSorting implements ISortable{
@Override
public Collection<String> sort(String[] strings) {
Collection<String> sorted = new Vector<String>();
//sort the elements and populate the sorted variable
return sorted;
}
}
精彩评论