有在你的代码的几个误区:
- 一个
Collection
不能作为数组([i]
符号)来访问。您已使用Iterator
进行适当的遍历。在遍历时使用它来访问这些值。
- 在该循环中访问
[i+1]
它具有定义的最终条件的方式很可能会抛出ArrayIndexOutOfBoundsException
。
- 你提到你需要返回一个新的列表,但你似乎试图重新排列在同一个
l1
Collection
中的元素。
- 不知道,如果它在你的代码中省略了,但你没有定义的引用变量
i
,也是最重要的,在整个循环迭代保持其价值。注意这个变量不是必需的,因为你已经使用迭代器遍历了Collection
。
我建议
- 遍历原来
Collection
因为你已经做。请记住使用iterator.next()
实际上使Iterator
继续前进并实际检索值。
- 将每个值插入到新列表中,但不仅仅在最后(使用
add(item)
)。寻找它应该进入(例如用while
或for
迭代循环的话),并使用List#add(int, E)
新元素拖放到它的地方转移下列元素右侧的位置的位置。这样,这个新的List
将保证始终有序。
- 阅读收藏和循环,并从Oracle的Java教程一个好的java教程,例如The Collection InterfaceLanguage Basics: The while statement可能是一个很好的起点。
只给一个起点/骨架,这里是它如何可能看起来像一个大纲:
public static Collection<Integer> sort(Collection<Integer> l1){
List<Integer> sortedList = new ArrayList<Integer>();
for (Iterator<Integer> it = l1.iterator(); it.hasNext();) {
Integer currentValue = it.next();
// Look into sortedList the position where currentValue should go into
int pos = 0;
for (int i=0;i<sortedList.size();i++) {
// Compare currentValue with sortedList.get(i)
// to know if i is the right position for currentValue.
// If it is, assign it to pos
}
sortedList.add(pos, currentValue);
}
return sortedList;
}
这是因为Java允许[]运算符只用于内置数组,如'new Integer [14]'。此外,'l1'是一个集合,它是(不像一个列表)没有排序,所以排序它是没有意义的。 我建议先通过一些Java基础教程。 – 2014-10-29 09:49:09
方括号语法不适用于Java中的集合。另外,不是每个集合都适合您的任务 - 您需要精确定制的集合。使用带有['.get(int)'](http://docs.oracle.com/javase/7/docs/api/java/util/List.html#get(int))方法的列表和访问元素,而不是方形的breckets。 – bsiamionau 2014-10-29 09:49:43
了解Array和ArrayList之间的区别 它们在java中是两个不同的东西 – 2014-10-29 10:03:11