如何将一个对象添加到另一个对象集中 [英] How to add an object into another Object set

查看:126
本文介绍了如何将一个对象添加到另一个对象集中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two classes. One(Person) for getters and setters, and another(People) for compute the data. What is my situation is, I get the data from the DB using ResultSet, then created a person Object to store the row data. Then i created people Object to store all persons.

每个对象都创建为 SET.

Each Object created as 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;

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

Now the problem is the last line in the While Loop people.add(person);

它说

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

The method add(People) in the type Set is not applicable for the arguments (Person)

我该如何克服这个问题?

How can i overcome this problem?

谢谢.

推荐答案

我从你的设计中了解到你有一个 People has-many Person 关系,所以 People 类包含 Person 对象的集合.然后我会期待这样的事情:

My understandig from your design is that you have a People has-many Person relation, so the People class holds a collection of Person objects. Then I'd expect something like this:

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, ...
}

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

So in your database related code you wouldn't need to create another set, because People already has the one you need:

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;

这篇关于如何将一个对象添加到另一个对象集中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆