2014-10-29 111 views
-1

到目前为止,我有使用[]运算符时为什么会出现编译错误?

public static void sort(Collection<Integer> l1){ 
Iterator<Integer> it = l1.iterator(); 
while(it.hasNext()){ //meant to be for(int i; i<l1.size(); i++) 
    if(l1[i] < l1[i+1]){ 
     l1[i] = l1[i+1]; 
     l1[i+1] = l1[i]; 
    } 

} 

我得到我的错误在我的if语句。

+1

这是因为Java允许[]运算符只用于内置数组,如'new Integer [14]'。此外,'l1'是一个集合,它是(不像一个列表)没有排序,所以排序它是没有意义的。 我建议先通过一些Java基础教程。 – 2014-10-29 09:49:09

+1

方括号语法不适用于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

+1

了解Array和ArrayList之间的区别 它们在java中是两个不同的东西 – 2014-10-29 10:03:11

回答

2

有在你的代码的几个误区:

  1. 一个Collection不能作为数组([i]符号)来访问。您已使用Iterator进行适当的遍历。在遍历时使用它来访问这些值。
  2. 在该循环中访问[i+1]它具有定义的最终条件的方式很可能会抛出ArrayIndexOutOfBoundsException
  3. 你提到你需要返回一个新的列表,但你似乎试图重新排列在同一个l1Collection中的元素。
  4. 不知道,如果它在你的代码中省略了,但你没有定义的引用变量i,也是最重要的,在整个循环迭代保持其价值。注意这个变量不是必需的,因为你已经使用迭代器遍历了Collection

我建议

  1. 遍历原来Collection因为你已经做。请记住使用iterator.next()实际上使Iterator继续前进并实际检索值。
  2. 将每个值插入到新列表中,但不仅仅在最后(使用add(item))。寻找它应该进入(例如用whilefor迭代循环的话),并使用List#add(int, E)新元素拖放到它的地方转移下列元素右侧的位置的位置。这样,这个新的List将保证始终有序。
  3. 阅读收藏和循环,并从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; 
} 
0

在一审中,迄今为止的意见是正确的。您不能像使用数组那样使用Collection。如果你声明

public static void sort(List<Integer> l1) 

然后toArray()方法可以用来获得数组。

其次,报表

l1[i] = l1[i+1]; 
    l1[i+1] = l1[i]; 

不可能工作,你会含有相同值的元素都结束了。

第三,我建议您将“快速排序”算法念起来和执行......这是不是所有的困难。下面是一个链接:http://www.vogella.com/tutorials/JavaAlgorithmsQuicksort/article.html

相关问题