【问题标题】:java.lang.ClassCastException: java.util.HashMap cannot be cast to java.lang.Comparablejava.lang.ClassCastException:java.util.HashMap 无法转换为 java.lang.Comparable
【发布时间】:2012-09-17 16:30:03
【问题描述】:

我正在尝试对我的 ArrayList 进行排序。

java.util.ArrayList arList= new java.util.ArrayList();  
   arList=getList();    
   java.util.Collections.sort(arList);

我的 getList() 函数在这里

public ArrayList getList() throws Exception
{
ArrayList listItems = new ArrayList();
//Query executing here..............!
            while (rs.next()) 
                {
                HashMap hashList = new HashMap();
                hashList.put("name",rs.getString(1));
                hashList.put("id",rs.getBigDecimal(2));
                listItems.add(hashList);
                }
          return listItems;
}

但是我遇到了错误:java.lang.ClassCastException: java.util.HashMap cannot be cast to java.lang.Comparable

【问题讨论】:

  • 您究竟是如何尝试对ArrayList 进行排序的?您的列表包含多个HashMaps。您是尝试根据地图的键还是地图的值对其进行排序?
  • 你为什么在这里使用HashMaps?您应该创建一个适当的对象类来保存名称和 ID。

标签: java sorting arraylist hashmap


【解决方案1】:

首先,您的代码看起来很奇怪,您在循环的每次迭代中都将一个新创建的 HashMap 对象添加到您的列表中。无论如何,我不会讨论它。也许你应该像这样指定你的 ArrayList:ArrayList<HashMap> 但这还不够。如果你有一个特定类型的列表并且想要对它们进行排序,那么你的 type(在本例中为 HashMap)应该实现Comparable 接口。 HashMap 没有实现Comparable 接口。阅读 API:http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html

我猜你应该实现自己的 Comparator 作为解决方案。

【讨论】:

    【解决方案2】:

    查看link

    列表中的所有元素都必须实现 Comparable 接口。此外,列表中的所有元素必须相互可比较(即,e1.compareTo(e2) 不得为列表中的任何元素 e1 和 e2 抛出 ClassCastException)。

    这应该说明一切。

    【讨论】:

      【解决方案3】:

      当然,编译器错误试图以最好的方式向您传达它无法比较列表中的HashMaps..

      首先,您应该像这样将您的列表声明为通用列表:-

      List<HashMap<String, String>> hashList = new ArrayList<>();
      

      如果你想对List&lt;HashMap&gt;进行排序,你需要有一个Comparator来排序..你不能使用自然排序来排序..因为你的HashMap没有实现Comparable接口..

      只有当两个实例具有可比性时,才能比较它们。

      *编辑:-嗯,我想你需要两个 Comparators 在这里.. 一个给你的 List 和一个给你的 HashMapList.. 但我不太确定有没有用..

      【讨论】:

        【解决方案4】:

        Collections.sort(List&lt;T&gt;) 需要 T 类型的 Comparable 对象。这意味着任何实现 Comparable 接口的对象都可以工作。参考[这个]( http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List%29):

         public static <T extends Comparable<? super T>> void sort(List<T> list)
        

        在您的情况下,您尝试对包含HashMapArrayList 进行排序,该Comparable 接口未实现。所以。代码失败。

        【讨论】:

          【解决方案5】:

          HashMap 没有实现 Comparable 接口 (http://docs.oracle.com/javase/6/docs/api/)。据我所知,Collections.sort()-Method 只能对自然值进行排序。但是您可以编写自己的比较器并根据需要对列表进行排序。因此 Collections.sort()-Method 被重载了

          【讨论】:

            【解决方案6】:

            对于要排序的东西,它必须实现Comparable 接口,这是HashMap 没有的。

            因此,当您尝试对 HashMap 列表进行排序时,您的代码会失败。

            如果您真的需要能够比较 HashMap,您可以创建自己的 HashMap,如下所示:

            public class MyHashMap<K,V> extends HashMap<K, V> implements Comparable<HashMap<K,V>>
            {
                ...
                public int compareTo(HashMap<K,V> comparer)
                {
                    ...
                }
            }
            

            【讨论】:

              【解决方案7】:

              为了使用Collections.sort(),实现此接口Comparable的对象列表(和数组)。 http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html

              【讨论】:

                【解决方案8】:

                猜测错误发生在 Collections.sort() 行。

                如果要使用排序,列表中的对象必须是 Comparable。不然java怎么排序呢?

                HashMap 不可比较。您可以扩展 HashMap 并实现 Comparable 接口。

                【讨论】:

                  【解决方案9】:

                  第一件事 -

                  java.util.ArrayList arList= new java.util.ArrayList();  
                  arList=getList();    
                  

                  您创建第一个实例是不必要的。

                  第二件事 -

                  ArrayList listItems = new ArrayList();
                  

                  此列表包含列表 HashMap 并且 HashMap 没有实现 Comparable。

                  java.util.Collections.sort(arList);
                  
                  public static <T extends Comparable<? super T>> void sort(List<T> list)
                  

                  列表包含(T) 必须扩展 Comparable。

                  这就是它填充java.lang.ClassCastException: java.util.HashMap cannot be cast to java.lang.Comparable的原因

                  【讨论】:

                    【解决方案10】:

                    是的,因为java.util.Collections.sort(arList); arList 包含HashMap hashList = new HashMap(); 不幸的是 hashMap 没有实现Comparable or Comparator interface.Collections.sort() 方法会在排序上执行

                     Comparable or Comparator interface.
                    

                    【讨论】:

                      【解决方案11】:

                      这样就可以实现一个Sorted Map

                      public class MapUsingSort {
                      public static void main(String[] args) {
                      
                      Map<Integer, String> abc = new HashMap<>();
                      abc.put(3, "a");
                      abc.put(6, "b");
                      abc.put(1, "c");
                      abc.put(4, "h");
                      abc.put(10, "k");
                      abc.put(9, "x");
                      
                       // Map is stored in ArrayList
                      List<Entry<Integer,String>> sortedEntries = new ArrayList<Entry<Integer,String>>(abc.entrySet());
                      
                      
                      Collections.sort(sortedEntries, new Comparator<Entry<Integer,String>>() {
                          @Override
                          public int compare(Entry<Integer, String> a, Entry<Integer, String> b) 
                          {
                              //Sorting is done here make changes as per your need 
                              // swap a and b for descending order 
                      
                              return a.getKey().compareTo(b.getKey());   
                          }
                         });
                      
                      for (Object object : sortedEntries) {
                      
                          //print your data in your own way
                          System.out.println((Map.Entry)object);
                         }
                        }
                      }
                      

                      更多详情请访问HashMap

                      *

                      这是我在 stackOverflow 上的第一个答案,希望对您有所帮助!

                      【讨论】:

                        猜你喜欢
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        相关资源
                        最近更新 更多