【问题标题】:Cannot find Collections.sort despite Comparable being implemented尽管实现了 Comparable,但找不到 Collections.sort
【发布时间】:2017-03-21 13:53:11
【问题描述】:

我在这里阅读了其他问题,发现当编译器为Collections.sort(List<T> list) 抛出Cannot find symbol 时,问题通常是......

  1. 没有通过List<T>
  2. List<T> 没有实现 Comparable
  3. 忘记导入java.util.Collection

我已经完成了所有这些事情,所以我怀疑我的实现在某种程度上是错误的。根据this 堆栈溢出条目和manual 我的实现应该是合法的,所以我没有想法。如果通过List<Item> 传递排序规则,规则会改变吗?

类似的实现

 public abstract class Item implements Comparable<Item>
  9 {
 ...//Fields and constructor omitted
 25     @Override
 26     public int compareTo(Item i)
 27     {
 28 //      String title = this.title; DEBUG FLAG: delete maybe?
 29         return this.title.compareTo(i.title); //Returns a negative value if title < i.title, implements alphabetical order by title
 30     }

在 Library.java 中调用(假设正确构建了 LinkedList 的 TreeMap)

 public Collection<Item> itemsForKeyword(String keyword)
 25     {
 26         List<Item> list;
 27         if(keywordDbase.get(keyword) == null) //There is no mapping at specified keyword
 28         {
 29             list = null;
 30         }
 31         else if(keywordDbase.get(keyword).isEmpty()) //There is a mapping but it is empty
 32             {
 33                 list = null;
 34             }
 35             else //There is a list that has at least one item in it
 36             {
 37                 list = keywordDbase.get(keyword); //stores a reference to the LinkedList in list
 38             }
 39
 40         Collections.sort(list); //DEBUG FLAG: Calling sort may be unnecessary 
 41
 42         return list; here
 43     }

错误

library/Library.java:40: error: cannot find symbol
                Collections.sort(list);
                ^

【问题讨论】:

  • 你需要导入java.util.Collections
  • 天哪。如果您发布答案,我会将其标记为已接受@shmosel

标签: java collections cannot-find-symbol


【解决方案1】:

Collectionsimport 语句丢失..

添加import java.util.Collections;

【讨论】:

    【解决方案2】:

    java.util.Collectionjava.util.Collections 不同。将以下导入语句添加到您的代码中:

    import java.util.Collections;`
    

    java.util.Collection

    集合层次结构中的根接口。集合表示一组对象,称为其元素。一些集合允许重复元素,而另一些则不允许。有些是有序的,有些是无序的。 JDK 不提供此接口的任何直接实现:它提供更具体的子接口(如 Set 和 List)的实现。此接口通常用于传递集合并在需要最大通用性的地方对其进行操作。

    另一方面,有一个类 java.util.Collections

    仅由对集合进行操作或返回集合的静态方法组成。它包含对集合进行操作的多态算法,“包装器”,它返回由指定集合支持的新集合,以及一些其他零碎的东西。

    它们是不同的,但处理的是同一个主题。不幸的是,您打错了字。

    【讨论】:

      猜你喜欢
      • 2022-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-05
      • 2016-11-01
      • 1970-01-01
      • 2021-10-27
      • 1970-01-01
      相关资源
      最近更新 更多