问题描述
我想为StringBuffer实现一个Comparator,它比较StringBuffer并相应地添加到TreeSet。这纯粹仅用于学习目的。我知道在Hasable集合中有一个可变对象是一个坏主意。但这里的目的是如何为Java的现有StringBuffer类实现比较器,并使用它来创建TreeSet。
我目前的代码如下。代码无法编译。请帮助我。谢谢
I want to implement a Comparator for StringBuffer that compares the StringBuffer and adds to TreeSet accordingly. This is purely for learning purposes only. I know having a mutable object in a Hasable collection is a bad idea. but the purpose here is how to implement comparator for existing StringBuffer class of Java and use it to create a TreeSet.My current code is below. The code does not compile. kindly help me out here. Thanks
public class ComparatorExample {
public class SbufferComparator implements Comparator<StringBuffer> {
@Override
public int compare(StringBuffer s1, StringBuffer s2) {
return s1.toString().compareTo(s2.toString());
}
}
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>(new SbufferComparator());
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);
}
}
推荐答案
你应该在不在同一个类中的单独文件中创建比较器类,或者如果你想让它保持内在,则将其设置为静态。
You should create the comparator class in a separate file not in the same class or make it static instead if you want to keep it inner.
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
public class ComparatorExample {
private static class SbufferComparator implements Comparator<StringBuffer> {
@Override
public int compare(StringBuffer s1, StringBuffer s2) {
return s1.toString().compareTo(s2.toString());
}
}
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>(new SbufferComparator());
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);
}
}
注意进口报表!
这篇关于如何在Java中为StringBuffer类实现比较器以便在TreeSet中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!