Student 資料物件程式如下 :
import java.io.Serializable;
@SuppressWarnings({ "serial", "rawtypes" })
public class Student implements Serializable {
private String name;
private String id;
private String address;
public Student(String name,String id, String address){
this.name=name;
this.id=id;
this.address=address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String toString(){
return name+","+id+","+address;
}
public boolean equals(Student x){
return name.equals(x.name);
}
public int hashCode(){
return name.hashCode();
}
}
因 Student 資料物件要由 HashSet 集合物件處理, 並且還要儲存到檔案, 所以 Student 資料物件程式必須覆寫 equals() , HashCode 這二個方法, 以及宣告實作 Serializable 介面. 可是以下程式對於相同的 Student 資料物件, 一樣會收集, 請找出此問題 ?
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class CreateMyClass {
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void main(String[] args) {
String [][] myclass = {
{"Tony","123","456"},
{"Rayn","345","890"},
{"apple","001","65455"},
{"apple","001","65455"}
};
Set s = new HashSet();
Student st=null;
for(String[] x : myclass) {
st = new Student(x[0],x[1],x[2]);
s.add(st);
}
Iterator iter = s.iterator ();
while (iter.hasNext ())
System.out.println (iter.next ());
}
}
2013年7月14日 星期日
訂閱:
張貼留言 (Atom)
No Response to "jAG304"
張貼留言