Java different sorting methods for one dataset

Suppose I collect n number of rows into an array or list of arrays or some other data structure. I want to come up with a design that will allow the user to determine how to sort the lines:

- If the user specifies parameter A, the lines will be placed in the vector, and then sorted and printed.

-If the user specifies option B, the lines will be placed in the list, and then sorted and printed.

I want my design to be flexible enough so that I can easily add additional sorting methods in the future (and my sorting methods).

My current implementation involves collecting rows from a user in an ArrayList, and then depending on the sorting method I will use Collections.copy (array, vector) or Collections.copy (array, list). Then I will do Collections.sort (vector or list).

(I am currently getting NullPointerExceptions on Collections.copy) ...

I'm not sure I'm going to do this in the best, most convenient way to use. Any thoughts?

Thank!

+3
source share
3 answers

You need to use the interfaces that Java provides. When you take an ArrayList, you force the implementation to the user. Take it Collection<String>, and they can use whatever they want.

List, List<String> . Vector, ArrayList, LinkedList ..

, Comparator Collections.sort(myList, myComparator);

, - ...

public List<String> sortThem(List<String> strings, Comparator<String> comp) {
    ... do cool things ...

    Collections.sort(strings, comp);

    return strings;
}
+3
0

Does this look like what you are looking for?

import java.util.Collection;

public interface ISortable {

    public Collection<String> sort(String[] strings);
}

And as an example of class implementation:

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

}

0
source

Source: https://habr.com/ru/post/1725230/


All Articles