尽管实施了 Comparable,但找不到 Collections.sort

Cannot find Collections.sort despite Comparable being implemented

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

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

我已经完成了所有这些事情,所以我怀疑我的实现有问题。根据 this stack overflow entry and the manual 我的实施应该是合法的,所以我没有想法。如果 sort 被传递 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);
                ^

缺少 Collectionsimport 语句..

添加import java.util.Collections;

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

import java.util.Collections;`

java.util.Collection

the root interface in the collection hierarchy. A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. The JDK does not provide any direct implementations of this interface: it provides implementations of more specific subinterfaces like Set and List. This interface is typically used to pass collections around and manipulate them where maximum generality is desired.

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

consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection, and a few other odds and ends.

它们各不相同,但围绕的是同一个主题。不幸的是,您刚刚打错了字。