简体   繁体   English

java.lang.ClassCastException:java.util.HashMap无法强制转换为java.lang.Comparable

[英]java.lang.ClassCastException: java.util.HashMap cannot be cast to java.lang.Comparable

I was trying to sort my ArrayList. 我试图对我的ArrayList进行排序。

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

where my getList() function here 我的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;
}

But I am facing error : java.lang.ClassCastException: java.util.HashMap cannot be cast to java.lang.Comparable 但我面临错误: java.lang.ClassCastException:java.util.HashMap无法强制转换为java.lang.Comparable

First Thing - 第一件事 -

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

You create the first instance unnecessary. 您创建不必要的第一个实例。

Second Thing - 第二件事 -

ArrayList listItems = new ArrayList();

This list contains list HashMap And HashMap does not implements Comparable. 此列表包含列表HashMap和HashMap未实现Comparable。

java.util.Collections.sort(arList);

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

List contain( T ) must extends Comparable. 列表包含( T )必须扩展Comparable。

that is why it populate java.lang.ClassCastException: java.util.HashMap cannot be cast to java.lang.Comparable 这就是为什么它填充java.lang.ClassCastException: java.util.HashMap cannot be cast to java.lang.Comparable

In order to use Collections.sort() , Lists (and arrays) of objects that implement this interface Comparable . 为了使用Collections.sort() ,实现此接口的对象的Lists(和数组) Comparable http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html

First of all, your code seems weird, you are adding a newly created HashMap object into your list in each iteration of the loop. 首先,您的代码看起来很奇怪,您在循环的每次迭代中将新创建的HashMap对象添加到列表中。 Anyway, I'll not discuss it. 无论如何,我不会讨论它。 Maybe you should specify your ArrayList like this: ArrayList<HashMap> But that is not enough. 也许你应该像这样指定你的ArrayList: ArrayList<HashMap>但这还不够。 If you have a list of a specific type and wanna sort them, then your type (in this case HashMap) should implement Comparable interface. 如果您有一个特定类型的列表并想要对它们进行排序,那么您的类型 (在本例中为HashMap)应该实现Comparable接口。 HashMap doesn't implement Comparable interface. HashMap不实现Comparable接口。 Read the API: http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html 阅读API: http//docs.oracle.com/javase/6/docs/api/java/util/HashMap.html

You should implement your own Comparator as a solution, I guess. 我猜你应该实现自己的比较器作为解决方案。

Check this link 检查此链接

All elements in the list must implement the Comparable interface. 列表中的所有元素都必须实现Comparable接口。 Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list). 此外,列表中的所有元素必须是可相互比较的(即,e1.compareTo(e2)不得为列表中的任何元素e1和e2抛出ClassCastException)。

This should say it all. 这应该说明一切。

Of course the compiler error is trying to convey you in the best way it can that it cannot compare HashMaps , that you have inside your list.. 当然,编译器错误试图以最好的方式传达给你,它无法比较你在列表中的HashMaps

First you should declare your list as generic list like this: - 首先,您应该将您的列表声明为通用列表,如下所示: -

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

If you want to sort List<HashMap> , you need to have a Comparator to sort.. You cannot sort it using natural ordering.. Because your HashMap does not implement Comparable interface.. 如果你想对List<HashMap>进行排序,你需要有一个Comparator来排序..你不能使用自然排序对它进行排序。因为你的HashMap没有实现Comparable接口..

You can only compare two instances if they are comparable.. 如果它们具有可比性,您只能比较两个实例。

*EDIT: - Well, I think you will need two Comparators here.. One for your List and one for your HashMap inside the List .. But I'm not pretty sure about it whether it would work.. *编辑: - 好吧,我想你在这里需要两个Comparators ..一个用于你的List ,一个用于你的HashMap里面的List ..但我不确定它是否会起作用..

Collections.sort(List<T>) requires an object T of type Comparable . Collections.sort(List<T>)需要一个Comparable类型的对象T That means any object that implements Comparable interface will work. 这意味着任何实现Comparable接口的对象都可以工作。 Refer [this]( http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List%29 ): 请参阅[this]( 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)

In your case you are trying to sort an ArrayList that contains a HashMap , which does not implements Comparable interface. 在您的情况下,您尝试对包含HashMapArrayList进行排序,该HashMap不实现Comparable接口。 So. 所以。 the code fails. 代码失败了。

HashMap does not implement the Comparable interface (http://docs.oracle.com/javase/6/docs/api/). HashMap没有实现Comparable接口(http://docs.oracle.com/javase/6/docs/api/)。 As far as I know the Collections.sort()-Method can only sort natural values.But you can write your own comparator and sort your list as you wish. 据我所知,Collections.sort() - 方法只能对自然值进行排序。但是你可以编写自己的比较器并根据需要对列表进行排序。 The Collections.sort()-Method is overloaded therefore 因此Collections.sort() - 方法被重载

For something to be sorted, it must implement the Comparable interface, which is something which the HashMap does not. 对于要排序的东西,它必须实现Comparable接口,这是HashMap没有的东西。

As a result, when you try to sort your list of HashMaps your code fails. 因此,当您尝试对HashMaps列表进行排序时,您的代码将失败。

If you really need to be able to compare HashMaps, you could create your own HashMap, something like so: 如果你真的需要能够比较HashMaps,你可以创建自己的HashMap,如下所示:

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

Yes, Because java.util.Collections.sort(arList); 是的,因为java.util.Collections.sort(arList); arList contains the HashMap hashList = new HashMap(); arList包含HashMap hashList = new HashMap(); unfortunately hashMap did not implement the Comparable or Comparator interface. 遗憾的是,hashMap没有实现Comparable or Comparator interface. and Collections.sort() method will sort on the implementation of Collections.sort()方法将对实现进行排序

 Comparable or Comparator interface.

Guess the error happened on line Collections.sort(). 猜猜在Collections.sort()行上发生的错误。

If you want to use sort, the objects in the list must be Comparable. 如果要使用排序,则列表中的对象必须为“可比较”。 Otherwise how java is gonna sort it? 否则java会如何排序呢?

HashMap is not Comparable. HashMap不是可比较的。 You can extend HashMap and implement Comparable interface. 您可以扩展HashMap并实现Comparable接口。

This way you can achieve a 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);
   }
  }
}

For further in detail visit HashMap 有关详细信息,请访问HashMap

* *

This is my first answer on stackOverflow hope it helps! 这是我在stackOverflow上的第一个答案希望它有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 java.lang.ClassCastException: 不能转换为 java.lang.Comparable - java.lang.ClassCastException: cannot be cast to java.lang.Comparable java.lang.ClassCastException:无法将java.util.HashMap强制转换为java.lang.String - java.lang.ClassCastException: java.util.HashMap cannot be cast to java.lang.String java.lang.ClassCastException:java.util.HashMap $ EntrySet无法转换为java.util.HashSet - java.lang.ClassCastException: java.util.HashMap$EntrySet cannot be cast to java.util.HashSet java.lang.ClassCastException: java.util.HashMap$EntrySet 不能转换为 java.util.Map$Entry - java.lang.ClassCastException: java.util.HashMap$EntrySet cannot be cast to java.util.Map$Entry java.lang.ClassCastException:尝试排序List时,java.util.LinkedHashMap无法转换为java.lang.Comparable异常 - java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to java.lang.Comparable exception when trying sort a List java.lang.ClassCastException: org.postgresql.util.PGobject 不能转换为 java.lang.Comparable; UUID转换器内部 - java.lang.ClassCastException: org.postgresql.util.PGobject cannot be cast to java.lang.Comparable; inside UUIDconverter 线程“主”java.lang.ClassCastException 中的异常:javafx.util.Pair 无法转换为 java.lang.Comparable - Exception in thread “main” java.lang.ClassCastException: javafx.util.Pair cannot be cast to java.lang.Comparable java.lang.ClassCastException:无法将java.util.HashMap强制转换为com.jms.testing.spring.InstructionMessage - java.lang.ClassCastException: java.util.HashMap cannot be cast to com.jms.testing.spring.InstructionMessage java.lang.ClassCastException:java.util.HashMap无法转换为自定义数据类 - java.lang.ClassCastException: java.util.HashMap cannot be cast to custom data class java.lang.ClassCastException: class java.util.Z063A5BC470661C3C7909 无法转换 - java.lang.ClassCastException: class java.util.HashMap cannot be cast : SpringBoot
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM