tags:

views:

164

answers:

3

Hello,

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!

A: 

http://stackoverflow.com/questions/689370/java-collections-copy-list-i-dont-understand

have a look at that - it will explain the null pointer

Aly
+1  A: 

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;
}
jcm
That makes sense to me, thank you!
A: 

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;
}

}

mheathershaw