TreeMap的一个错误 ...cannot be cast to java.lang.Comparable
今天在页面使用jstl的<c:froEach>遍历HashMap
<c:forEach items="${ydMap }" var="m"><div /></a>:</div><div var="l"><span /></a></span></c:forEach></div></div></c:forEach>但是每次刷新时顺序都会变化,原来HashMap是遍历时是无序的!如是就想到使用TreeMap
Map<BaseState,List<BlackChannelStates>> map=new TreeMap<BaseState,List<BlackChannelStates>>();
BaseState的代码 如下:
public class BaseState implements Comparable<BaseState>{private Integer id;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}}但是使用后就一直报, ...cannot be cast to java.lang.Comparable
查看了TreeMap的原码发现HashMap有如下的构造方法:
public TreeMap(Comparator<? super K> comparator) { this.comparator = comparator; }原来TreeMap是有序的,有序就说明TreeMap中的每个Key元素都需要能比较,只有这样才能排序。如是我就在BaseState这个Bean改成了如下:
public class BaseState implements Comparable<BaseState>{private Integer id;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}@Overridepublic int compareTo(BaseState o) {// TODO Auto-generated method stubreturn o.getId()-this.getId();}}此时再调用这个错误解决了!