考你一个小问题:"1000000.0"是一个什么类型的常量?备选答案:(a)String,(b)float
解决方案 »
- Quartz设置每小时的第10分钟执行如何写CronExpression表达式
- 今天学了接口 可不知道他是如何实例化的
- 一个关于Socket的问题
- rmi 多线程机制 望指点!!!
- AWTEventMulticaster在管理TextListener时出现问题, 请专家解答
- 小弟跪求高手解决,在线等.: input事先附好值,如果上中文取得时就是乱码
- path设置!在线
- 谁有漂亮的LookAndFeel第三方包,麻烦给小弟发个,或是给个下载地址! 谢谢啦!^_^
- 急!请教一个问题:如何在TableView中加上Button?(100分)
- 运行一个java程序时遇到的问题
- 如何编写网站自动登陆程序?
- 关于jbuilder的问题!!!!!!!!!
Car的构造方法:Car(float,String),而你调用的是Car(String,String),
所以new Car("1000000.0", "Benz")会出错。
改为:new Car(1000000.0f, "Benz")就可以了(注意有小数点的默认为double类型,所以后面要加上f)
// 1000000.0 应该用double了.import java.util.*;class Car
{
double price;
String brand;
Car(double price, String brand)
{
this.price = price;
this.brand = brand;
}
/*
public boolean equals(Object o){ //....}
public int hashCode(){//...}
*/
}public class Test
{
public static void main(String[] args)
{
Set s = new TreeSet();
s.add(new Car(1000000.0, "Benz"));
s.add(new Car(2888888.88, "Bently"));
System.out.println(s);
}
}
而调用时用的是"1000000.0" 这是string型,肯定是不对的。
s.add(new Car(1000000.0, "Benz"));
s.add(new Car(2888888.88, "Bently"));
可是这样有错,当我注释掉上面任何一句时,程序就可以正常运行了.这是为什么呢?
望大虾们帮忙看看,小弟先谢谢了!
price 用 double 就行了. :)
public int compareTo(Object o) {
return X;
}
X--> 如果X=0,就在treeset中添加一个object,如果是其他的值就可以添加好多
你也可以看看我写好的code
import java.util.*;public class TestTreeSet implements Comparable
{
private double price;
private String brand;
TestEncoding(double price, String brand){
this.price = price;
this.brand = brand;
}
public static void main(String[] args)
{
Set s = new TreeSet();
s.add(new TestTreeSet(1000000.0, "Benz"));
s.add(new TestTreeSet(2888888.88, "Bently"));
System.out.println(s.size());
}
public int compareTo(Object o) {
return 3;
}
}
这个问题涉及到了数据结构的黑白树的概念
Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.注意里面的这句:but a TreeSet instance performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the set, equal.
这就是你出错的原因,你使用了TREESET,但是没有正确得重写compareTo方法。