假设我正在将数量的字符串收集到数组,数组列表或其他一些数据结构中。我想提出一个设计,允许用户指定字符串的排序方式:
- 如果用户指定选项A,则将字符串放入Vector中,然后进行排序和打印。
- 如果用户指定选项B,则字符串将被放入列表中,然后进行排序和打印。
我希望我的设计足够灵活,以便将来可以轻松添加其他排序方法(以及我的排序方法)。
我当前的实现涉及从用户收集字符串到ArrayList,然后根据指定的排序方法,我将使用Collections.copy(array,vector)或Collections.copy(array,list)。然后,我将执行Collections.sort(向量或列表)。
(目前,我在Collections.copy上收到NullPointerExceptions)...
我不确定我是否会以最好,最可重复使用的方式解决这个问题。有什么想法吗?
谢谢!
答案 0 :(得分:3)
您需要使用Java提供的接口。当您接收ArrayList时,您正在强制执行用户。接受Collection<String>
,他们可以使用他们想要的任何东西。
如果您想强制它们进入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;
}
答案 1 :(得分:0)
Java Collections copy list - I don't understand
看一下 - 它将解释空指针
答案 2 :(得分:0)
这与您正在寻找的相似吗?
import java.util.Collection;
public interface ISortable {
public Collection<String> sort(String[] strings);
}
作为实现类的一个例子:
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;
}
}