arraylist在java中返回包含元素的名称的方法?
Java初学者,我想通过函数“readPeople()”返回ArrayList“this.list”中的名称,这要感谢用户提供的id。 这是我的密码:
public class PersonneC implements PersonneDB {
this.list = new ArrayList();
People marie = new People(1, "Bower", "Marie");
list.add(marie.toString());
public PeopleWithId readPeople(int idPeople) {
PeopleWithId peoplename = null;
for(int i = 0; i < list.size(); i++) {
if(liste.get(i).equals(idPeople)) {
result = list.get(i);
}
}
return result.getPeopleName(); //ERROR INCOMPATIBLE TYPES
}
Wanted result returned: Bower
# 1 楼答案
您的方法返回一个
string
,而readPeople
的返回类型是PeopleWithId
# 2 楼答案
# 3 楼答案
您得到不兼容类型的原因是,在函数readPeople中,您告诉它返回PeopleWithId,其中返回的是字符串
由于此对象不存在,公共修饰符更改PeopleWithId后,将其更改为字符串。这样做的目的是告诉函数要从中获取的对象类型,在本例中是字符串,因为您的名称已存储为字符串