有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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


共 (3) 个答案

  1. # 1 楼答案

    您的方法返回一个string,而readPeople的返回类型是PeopleWithId

  2. # 2 楼答案

    ArrayList<People> list = new ArrayList<>();
    
    // add people to the list
    People marie = new People(1, "Bower", "Marie");
    list.add(marie);
    
    // Search function
      public String readPeople(int idPeople) {
        People p = null;
        for(int i = 0; i < list.size(); i++) {
            // If equal than it is the result
            if(list.get(i).id == idPeople) {
                p = list.get(i);
                break;
            }
        }
        return p == null ? null : p.getName();
      }
    
  3. # 3 楼答案

    您得到不兼容类型的原因是,在函数readPeople中,您告诉它返回PeopleWithId,其中返回的是字符串

    由于此对象不存在,公共修饰符更改PeopleWithId后,将其更改为字符串。这样做的目的是告诉函数要从中获取的对象类型,在本例中是字符串,因为您的名称已存储为字符串