【Java报错】java.lang.ClassCastException: xxxClass cannot be cast to java.lang.Comparable 问题重现+解决
生活随笔
收集整理的這篇文章主要介紹了
【Java报错】java.lang.ClassCastException: xxxClass cannot be cast to java.lang.Comparable 问题重现+解决
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
報(bào)錯(cuò)信息:java.lang.ClassCastException: xxx cannot be cast to java.lang.Comparable
1. 問題重現(xiàn)
以下為偽代碼:
// 獲取的List對(duì)象集合List<SomeRes> someResList = service.getSomeResList();// 要放入的Set集合Set<SomeRes> someResSet = null;for (SomeRes res : someResList ) {someResSet = new TreeSet<>();someResSet.add(res);}原因分析:
第一次添加元素時(shí),因?yàn)門reeSet或者TreeMap對(duì)象為空,不需要比較,不會(huì)報(bào)錯(cuò)。但是當(dāng)?shù)诙畏湃朐貢r(shí),TreeSet或者TreeMap為了確保對(duì)象有序的就必須比較,這個(gè)時(shí)候發(fā)現(xiàn)這兩個(gè)對(duì)象根本無法比較,則拋出該異常錯(cuò)誤。實(shí)際上在new TreeSet<>(); 時(shí)idea已經(jīng)提示(Construction of sorted collection with non-comparable elements 構(gòu)造具有非可比元素的排序集合)。
2. 問題解決
非可排序的類實(shí)現(xiàn) Comparable 接口,并重寫 compareTo 方法:
public class SomeRes implements Comparable<SomeRes> {@ApiModelProperty(value = "設(shè)備ID")@JsonProperty(value = "equip")private String equip;@ApiModelProperty(value = "車牌號(hào)")@JsonProperty(value = "car_number")private String carNumber;@Overridepublic int compareTo(@NotNull SomeRes o) {return this.carNumber.compareTo(o.carNumber);} }總結(jié)
以上是生活随笔為你收集整理的【Java报错】java.lang.ClassCastException: xxxClass cannot be cast to java.lang.Comparable 问题重现+解决的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Tomcat【环境搭建 02】Web端4
- 下一篇: 【Java报错】借助@PostConst