作者rukawa0328 (卡)
站内java
标题Re: [问题] HashSet 比较物件时的问题
时间Mon Sep 15 13:45:45 2008
※ 引述《inthehope ()》之铭言:
: 有个自订类别
: public class Node {
: public Node(String name,String type){
: this.name = name;
: this.type = type;}
: public int hashCode() {
: int result;
: result = this.name.hashCode();
: return result;}
: public boolean equals(Object other){
: if(((Node)other).name.equals(this.name))
: return true;
: return false;}
: }
: public static void main(String[] args)
: {
: Node n = new Node("Lin","Human");
: Node k = new Node("Lin","alien");
: public static Set<Node> set = new LinkedHashSet<Node>();
: set.add(n);
: set.add(k); //会视为相同物件,不加入set
: 想请问有办法在判断是相同物件时执行我想自订的方法吗?
: 比如说:当set.add(k)时发现set里面有相同物件时执行System.out.print("已有相同物");
: }
// 借一下你的main method.........XD
public static void main(String[] args) {
Node n = new Node("Lin","Human");
Node k = new Node("Lin","alien");
Set set = new LinkedHashSet() {
public boolean add(Object o) {
boolean retval = super.add(o);
if (!retval)
System.out.print("已有相同物");
return retval;
}
};
set.add(n);
set.add(k); //会视为相同物件,不加入set
}
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 218.211.164.2
1F:→ rukawa0328:不好意思 不习惯5.0的写法 故改成旧的写法.... 09/15 13:47
※ 编辑: rukawa0328 来自: 218.211.164.2 (09/15 15:22)
2F:推 inthehope:哇~感谢 :) 09/15 17:47