看板 java 關於我們 聯絡資訊
※ 引述《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
rukawa0328:不好意思 不習慣5.0的寫法 故改成舊的寫法.... 09/15 13:47
※ 編輯: rukawa0328 來自: 218.211.164.2 (09/15 15:22)
inthehope:哇~感謝 :) 09/15 17:47