在 Java 中反转通用集合
Reverse a generic collection in Java
我有以下任务:
"声明一个方法,期望一个集合并在你的方法中反转它。Return给定相同的集合,不要[=28=]一个新集合!
static <T> void reverse (Collection<T> collection)
不要尝试使用 Collections.reverse。它仅适用于列表,不适用于集合
我最初的想法是:
public static <T> void reverse(Collection<T> collection){
int size = collection.size();
Iterator<T> iter = collection.iterator();
Iterator<T> iter2 = collection.iterator();
for (int i = 0; i < size / 2; i++) {
collection.add(iter.next());
iter2.remove();
}
}
但我不断收到奇怪的异常:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at ReverseCollection.reverse(ReverseCollection.java:16)
at ReverseCollection.main(ReverseCollection.java:25)
知道应该怎么做吗?
你想做的不能做,因为很多Collection
类(比如HashSet
)不让你控制顺序。
问题是一般Collection
中元素的顺序没有定义。例如,想想 Set
,它不保证元素的顺序。
由于没有顺序,所以很难定义什么是倒序。
虽然任务通常是不可能的(例如对于不可变集合,以及不按插入顺序迭代的集合),您可以反转任何保留插入顺序的集合以及可选的 clear
和 addAll
实现如下:
<T, C extends Collection<T>> C reverse(C in) {
// Copy the contents of the collection into a new list.
List<T> list = new ArrayList<>(in);
// Remove everything from the original container.
in.clear();
// Reverse the list.
Collections.reverse(list);
// Put everything back into the original container.
in.addAll(list);
// If addAll is not supported, but add is, you can do
// for (T t : list) { in.add(t); }
return in;
}
对于未保留插入顺序的集合,这可能会或可能不会导致不同的顺序(例如,HashSet
可能不同;TreeSet
不会不同).
我有以下任务:
"声明一个方法,期望一个集合并在你的方法中反转它。Return给定相同的集合,不要[=28=]一个新集合!
static <T> void reverse (Collection<T> collection)
不要尝试使用 Collections.reverse。它仅适用于列表,不适用于集合
我最初的想法是:
public static <T> void reverse(Collection<T> collection){
int size = collection.size();
Iterator<T> iter = collection.iterator();
Iterator<T> iter2 = collection.iterator();
for (int i = 0; i < size / 2; i++) {
collection.add(iter.next());
iter2.remove();
}
}
但我不断收到奇怪的异常:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at ReverseCollection.reverse(ReverseCollection.java:16)
at ReverseCollection.main(ReverseCollection.java:25)
知道应该怎么做吗?
你想做的不能做,因为很多Collection
类(比如HashSet
)不让你控制顺序。
问题是一般Collection
中元素的顺序没有定义。例如,想想 Set
,它不保证元素的顺序。
由于没有顺序,所以很难定义什么是倒序。
虽然任务通常是不可能的(例如对于不可变集合,以及不按插入顺序迭代的集合),您可以反转任何保留插入顺序的集合以及可选的 clear
和 addAll
实现如下:
<T, C extends Collection<T>> C reverse(C in) {
// Copy the contents of the collection into a new list.
List<T> list = new ArrayList<>(in);
// Remove everything from the original container.
in.clear();
// Reverse the list.
Collections.reverse(list);
// Put everything back into the original container.
in.addAll(list);
// If addAll is not supported, but add is, you can do
// for (T t : list) { in.add(t); }
return in;
}
对于未保留插入顺序的集合,这可能会或可能不会导致不同的顺序(例如,HashSet
可能不同;TreeSet
不会不同).