0

我正在尝试将对象添加到我的 ArrayList 朋友...我收到此错误,

ArrayList 类型中的方法 add(int, Person) 不适用于参数 (int, String)

我正在尝试添加我的人对象的一些实例以最终创建一棵朋友树。

import java.util.*;

public class Person
{
    public int     id;     // some identification number unique to the person
    public boolean zombie; // true if the person is a zombie
    public char    state;  // p means human, z means zombie

    public static ArrayList<Person> friends;  // list of friends

    public Person(int id, char state)
    {
        this.id = id;
        this.state = state;
        //this.zombie = zombie;
    }

    public static void addPeople() 
    {
        friends = new ArrayList<Person>();
        friends.add(1, 'p');
    }

    public boolean isZombie() 
    {
        if (state == 'p')
        {
            return zombie=false;
        }
        else if (state == 'z')
        {
            return zombie=true;
        }

        return zombie;  
    }
}

该错误位于“添加”字下。我还想知道如何命名对象的实例,所以我只调用名称而不是两个属性。

提前感谢所有帮助。

4

2 回答 2

3
import java.util.ArrayList;
import java.util.List;

/**
 * Person description here
 * @author Michael
 * @link http://stackoverflow.com/questions/15799429/why-am-i-getting-this-error-when-adding-object-to-arraylist-java/15799474?noredirect=1#comment22468741_15799474
 * @since 4/3/13 9:45 PM
 */
public class Person {
    private Integer id;
    private boolean zombie;
    private List<Person> friends;

    public static void main(String [] args) {
        List<Person> lastPeopleStanding = new ArrayList<Person>();
        for (int i = 0; i < 3; ++i) {
            lastPeopleStanding.add(new Person(i));
        }
        lastPeopleStanding.get(0).addFriend(lastPeopleStanding.get(1));
        lastPeopleStanding.get(0).addFriend(lastPeopleStanding.get(2));
        System.out.println(lastPeopleStanding);
    }

    public Person(Integer id) {
        this.id = id;
        this.zombie = false;
        this.friends = new ArrayList<Person>();
    }

    public boolean isZombie() { return this.zombie; }

    // Irreversible!  Once you go zombie, you don't go back
    public void turnToZombie() { this.zombie = true; }

    // Only add a friend if they're not a zombie
    public void addFriend(Person p) {
        if (p != null && !p.isZombie()) {
            this.friends.add(p);
        }
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Person{");
        sb.append("id=").append(id);
        sb.append(", zombie=").append(zombie);
        sb.append(", friends=").append(friends);
        sb.append('}');
        return sb.toString();
    }
}
于 2013-04-03T22:37:17.093 回答
1

您忘记创建一个新Person的添加到您的ArrayList

根据您的评论,您可以创建一个名为idCount并在添加 a 时递增的类成员变量Person

public void addPeople() {
    friends.add(new Person(++idCount, 'p'));
}

对于可以具有状态的类,使用static方法通常被认为是糟糕的设计。

于 2013-04-03T22:37:53.150 回答