オブジェクトを一意のフィールドで塗りつぶすにはどうしたらいいですか?一意のフィールドを持つオブジェクトを追加する方法
たとえば、name
と呼ばれる一意のフィールドを持つクラスPerson
があります。したがって、重複する名前のオブジェクトを追加する場合は、追加しないでください。これをachiveする
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Set<Person> objList = new HashSet<Person>();
objList.add(new Person("John", "New York", "Accountant"));
objList.add(new Person("Bill", "London", "Manager"));
objList.add(new Person("John", "New York", "Driver"));// this object should not be added
for(Person o : objList){
System.out.println(o.name);//here should printed only John and Bill
}
}
}
class Person {
String name;//must be unique
String city;
String position;
public Person(String c_name, String c_city, String c_position){
this.name = c_name;
this.city = c_city;
this.position = c_position;
}
}
可能な複製http://stackoverflow.com/questions/16009027/java-collection-of-unique-elements。 –
Neria Nachum、私は、私の例ではhashCodeとequalsメソッドをオーバーライドする方法を理解できません。 – gigs
それのためのGoogle。または、IDEに生成させるよう依頼し、コードを理解し、javadocで定義されているコントラクトをコンパイルする方法を理解してみてください。 –