的StringBuffer对象可以成为Java中TreeSet中的键吗? [英] can StringBuffer objects be keys in TreeSet in Java?

查看:109
本文介绍了的StringBuffer对象可以成为Java中TreeSet中的键吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,我试图将StringBuffer对象作为TreeSet中的键。我这样做的原因是看是否可以将可变对象用作键。我没有任何编译错误。但是当我运行此代码时,我得到了代码下方的错误。特别是
,我得到了这个 java.lang.StringBuffer无法转换为java.lang.Comparable 。该错误表示什么?

I have the following code where I am trying to put the StringBuffer objects as keys in a TreeSet. The reason I do this is to see if I can put mutable objects as keys. I do not get any compile error. but when I run this code, I get the error that is below the code. specially, I get this java.lang.StringBuffer cannot be cast to java.lang.Comparable. what does this error indicate?

我看到StringBuffer类被声明为final( public final class StringBuffer ) ,不是说它是不可变的,因此是可哈希的吗?

from javadoc I see that StringBuffer class is declared final (public final class StringBuffer), doesn't that mean it is immutable and hence hashable?

我是哈希和不可变的东西的新手,请在这里帮助我。

I am a newbie to the hashing and immutable stuff, so kindly help me out here.

谢谢

import java.util.*;
class MutableKeys {
public static void main(String[] args) {
        StringBuffer one = new StringBuffer("one");
        StringBuffer  two = new StringBuffer("two");
        StringBuffer three = new StringBuffer("three");
        Set<StringBuffer> sb=new TreeSet<StringBuffer>();
        sb.add(one);
        sb.add(two);
        sb.add(three);
        System.out.println("set before change: "+ sb);
        one.append("onemore");
        System.out.println("set After change: "+ sb);
    }
}

Exception in thread "main" java.lang.ClassCastException: java.lang.StringBuffer cannot be cast to java.lang.Comparable
    at java.util.TreeMap.put(TreeMap.java:542)
    at java.util.TreeSet.add(TreeSet.java:238)
    at inheritance.MutableKeys.main


推荐答案

只需添加一个比较器类,然后在TreeSet中使用它,如下所示:

just add a comparator class and then use it in your TreeSet as follows:

class Comparatorbuff implements Comparator<StringBuffer> {

        @Override
        public int compare(StringBuffer s1, StringBuffer s2) {
            return s1.toString().compareTo(s2.toString());

        }

}

in your main method: modify as follows
Set<StringBuffer> sb=new TreeSet<StringBuffer>(new Comparatorbuff());

这篇关于的StringBuffer对象可以成为Java中TreeSet中的键吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆