本人正在看TIJ3,碰到一个问题,如果你能解决这个问题并且正在看TIJ的话进来加个好友
9.帮我看看这个输出,怎么我的Set中存在有重复元素。
A君答:你需要在class MyType实现public int hashCode()这个方法。
B君答:在类MyType重定义equals或compareTo方法试一下。
代码如下:
import java.util.*;
/**
* @author Administrator
*
* 更改所生成类型注释的模板为
* 窗口 > 首选项 > Java > 代码生成 > 代码和注释
*/
class MyType{
private int i ;
public MyType(int i){
this.i = i ;
}
public String toString(){
return "MyType id:"+ i ;
}
}
public class Set2 {
private static Set fill(Set a , int size){
for(int i = 0 ;i
a.add(new MyType(i)) ;
}
return a ;
}
public static void test(Set a){
fill(a , 10) ;
System.out.println(a) ;
fill(a , 10) ;
System.out.println(a) ;
}
public static void main(String[] args) {
test(new HashSet()) ;
}
}
输出结果如下:
[MyType id:9, MyType id:1, MyType id:3, MyType id:5, MyType id:2, MyType id:7, MyType id:0, MyType id:8, MyType id:4, MyType id:6]
[MyType id:9, MyType id:4, MyType id:3, MyType id:1, MyType id:8, MyType id:9, MyType id:3, MyType id:2, MyType id:5, MyType id:2, MyType id:7, MyType id:5, MyType id:0, MyType id:1, MyType id:8, MyType id:6, MyType id:0, MyType id:6, MyType id:7, MyType id:4]
TIJ3的那一节没看完,再接着看好像就有答案了~~~
msn: liuyaoliusos@hotmail.com