如何将对象添加到另一个对象集中

4 java object set

我有两节课.一个(Person)用于getter和setter,另一个(People)用于计算数据.我的情况是,我从数据库中获取数据ResultSet,然后创建一个人对象来存储行数据.然后我创建了人物对象来存储所有人.

每个对象创建为SET.

while(rs.next())
{
    Set<People> people = new HashSet<people>();
    Person person = new Person();
    String name = rs.getString(2);
    person.setName(name);
    int id = rs.getInt(1);
    person.setId(id);
    String dept = rs.getString(4);
    person.setDept(dept);
    int age = rs.getInt(3);
    person.setAge(age);
    people.add(person);
}
return people;
Run Code Online (Sandbox Code Playgroud)

现在问题是While循环中的最后一行 people.add(person);

它说

类型Set中的方法add(People)不适用于参数(Person)

我怎样才能克服这个问题?

谢谢.

And*_*s_D 9

我的设计理解是你有一个People has-many Person关系,所以这个People类拥有一个Person对象集合.然后我会期待这样的事情:

public class Person {
  private String name;
  private Date dateOfBirth;
  // .. more attributes

  // getters and setters

  // overrides of equals, hashcode and toString
}

public class People implements Set<Person> {
  private Set<Person> persons = new HashSet<Person>();

  public boolean add(Person person) {
    return persons.add(person);
  }

  // more methods for remove, contains, ...
}
Run Code Online (Sandbox Code Playgroud)

因此,在您的数据库相关代码中,您不需要创建另一个集合,因为People已经拥有您需要的集合:

People people = new People();  // or get it, if it's already created
while(rs.next())
{
    Person person = new Person();
    String name = rs.getString(2);
    person.setName(name);
    int id = rs.getInt(1);
    person.setId(id);
    String dept = rs.getString(4);
    person.setDept(dept);
    int age = rs.getInt(3);
    person.setAge(age);
    people.add(person);
}
return people;
Run Code Online (Sandbox Code Playgroud)