我正在尝试将对象添加到我的ArrayList朋友......我收到此错误,
ArrayList类型中的方法add(int,Person)不是 适用于参数(int,String)
我正在尝试添加我的person对象的一些实例,最终创建一个朋友树。
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;
}
}
错误位于“添加”字下。我还想知道如何命名对象的实例,所以我只调用名称而不是两个属性。
提前感谢您的帮助。
答案 0 :(得分: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();
}
}
答案 1 :(得分:1)
您忘记创建新的Person
以添加到ArrayList
:
从您的评论中,您可以创建一个名为idCount
的类成员变量,并在添加Person
时递增:
public void addPeople() {
friends.add(new Person(++idCount, 'p'));
}
对于可以拥有状态的类,使用static
方法通常被认为是糟糕的设计。