Tag: 可比较的

从具有子类的抽象类实现Comparable接口

package geometricobject; public abstract class GeometricObject implements Comparable { private String color = “white”; private boolean filled; private java.util.Date dateCreated; protected GeometricObject(){ dateCreated = new java.util.Date(); } protected GeometricObject(String color, boolean filled){ dateCreated = new java.util.Date(); this.color = color; this.filled = filled; } public String getColor(){ return color; } public void setColor(String color){ this.color = […]

可以将StringBuffer对象作为Java中TreeSet中的键吗?

我有以下代码,我试图将StringBuffer对象作为键设置在TreeSet中。 我这样做的原因是看我是否可以将可变对象作为键。 我没有得到任何编译错误。 但是当我运行此代码时,我得到的代码下面的错误。 特别是,我得到这个java.lang.StringBuffer cannot be cast to java.lang.Comparable 。 这个错误表明了什么? 从javadoc我看到StringBuffer类被声明为final( public final class StringBuffer ),这是不是意味着它是不可变的,因此可以散列? 我是哈希和不变的东西的新手,所以请在这里帮助我。 谢谢 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 sb=new TreeSet(); sb.add(one); sb.add(two); sb.add(three); System.out.println(“set before change: […]

使用TreeMap时Java“无法转换为Comparable”

可能重复: Java:SortedMap,TreeMap,Comparable? 如何使用? 我正在使用Java JungI图形包和Netbeans 7.我从Java得到以下错误: Exception in thread “main” java.lang.ClassCastException: graphvisualization.MyVertex cannot be cast to java.lang.Comparable at java.util.TreeMap.put(TreeMap.java:542) 以下是与错误相关的代码: SortedMap vMap = new TreeMap(); double curRank = 0; for(MyVertex v: g.getVertices()) //g is a SparseGraph { curRank = vertexRank.getVertexScore(v); vMap.put(v, curRank); //**Here is my Error** } MyVertex类是我为图表制作的一个类。 以下是MyVertex的代码 public class MyVertex { int vID; […]

实现Comparable,compareTo名称冲突:“具有相同的擦除,但不会覆盖其他”

我想有一个compareTo方法,它接受一个Real(一个用于处理任意大而精确的实数的类[好吧,只要它的长度小于2 ^ 31])和compareTo方法一个对象,但Java不让我,我没有足够的经验知道为什么。 我只是尝试修改类来实现Comparable,我在下面收到了这些错误消息。 我真的不明白错误信息是什么意思,但我知道它与我可怕的方式有关,我试图给我的课程一些灵活性,为我制作的每一种方法提供所有不同的方法签名,我可以解决它通过删除compareTo(Object other)方法,但我最好保留它。 所以我真正要问的是:有没有办法让这些错误消息消失而不删除compareTo(Object other)方法,这些错误究竟是什么意思? 另外,我知道已经有一些像BigInteger这样的内置Java类以及我正在尝试使用这个类的东西,但我正在为了与Project Euler( https://一起使用)的乐趣/满足感而这样做projecteuler.net/ )。 Jake@Jake-PC /cygdrive/c/Users/Jake/Documents/Java/Mathematics $ javac Real.java Real.java:377: error: name clash: compareTo(Real) in Real overrides a method whose erasure is the same as another method, yet neither overrides the other public int compareTo(Real other) ^ first method: compareTo(Object) in Real second method: compareTo(T) in Comparable […]