我有两个类(class)。一个(人)用于 getter 和 setter,另一个(人)用于计算数据。我的情况是,我使用 ResultSet
从数据库中获取数据,然后创建了一个 person 对象来存储行数据。然后我创建了 people 对象来存储所有的人。
每个对象创建为 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);
它说
The method add(People) in the type Set is not applicable for the arguments (Person)
我怎样才能克服这个问题?
谢谢。
最佳答案
我从你的设计中了解到你有一个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, ...
}
因此在与数据库相关的代码中,您不需要创建另一组,因为 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;
关于java - 如何将对象添加到另一个对象集中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3545183/