日期:2014-05-20  浏览次数:20825 次

TreeSet加了判断还是有重复元素
package src;
import java.util.*;
class T2{
public int id;
public String name;

public T2(int id,String name){
this.id=id;
this.name=name;
}
public int HashCode(){
int i=this.id+name.hashCode();
return i;
}

public boolean equals(Object p){
if(p==null){
return false;
}
if(this==p){
return true;
}
if(p instanceof T2){
T2 t=(T2)p;
if(this.id==t.id&&this.name.equals(t.name)){
return true;
}
}
return false;
}
public String toString(){
return this.id+"-----------"+this.name;
}
}

public class T1 {


public static void main(String[] args) {
Set<T2> s=new HashSet();

s.add(new T2(1,"A"));
s.add(new T2(5,"c"));
s.add(new T2(3,"d"));
s.add(new T2(4,"e"));
s.add(new T2(4,"e"));
Iterator<T2> it=s.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}

}
TreeSet排序

------解决方案--------------------
楼主重写hashCode写错了,首字母是小写的,注意JAVA是区分大小写的啊
------解决方案--------------------
HashCode写错了吧,hashCode才对吧?
------解决方案--------------------
public int HashCode(){ //这个是你的代码,这里写错了。注意大小写!
下面是我写的代码,可以正确运行。

package com.wanmei.test;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

class T2 {
private int id;
private String name;

public T2(int id, String name) {
super();
this.id = id;
this.name = name;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 17;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
T2 other = (T2) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}

public String toString() {
return this.id + "-----------" + this.name;
}
}

public class T1 {

public static void main(String[] args) {
Set<T2> s = new HashSet<T2>();

s.add(new T2(1, "A"));
s.add(new T2(5, "c"));
s.add(new T2(3, "d"));
s.add(new T2(4, "e"));
s.add(new T2(4, "e"));
Iterator<T2> it = s.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}

}

------解决方案--------------------
public int HashCode(){
int i=this.id+name.hashCode();
return i;
}

hashCode()你把h大写了,改一下就可以了