TreeSet加了判断还是有重复元素

jsfbjebjef 2013-11-29 08:24:47
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());
}
}

}
...全文
207 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
public int HashCode(){ int i=this.id+name.hashCode(); return i; } hashCode()你把h大写了,改一下就可以了
  • 打赏
  • 举报
回复
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());
		}
	}

}
  • 打赏
  • 举报
回复
可以结贴了!
小绵羊 2013-11-29
  • 打赏
  • 举报
回复
HashCode写错了吧,hashCode才对吧?
  • 打赏
  • 举报
回复
楼主重写hashCode写错了,首字母是小写的,注意JAVA是区分大小写的啊

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧