我解决了这个问题:
1-定义(覆盖)toString 方法来打印人名、年龄和他/她的朋友名单。
2-定义一个返回一个人的朋友数量的方法。
3-定义一个getter方法,将一个人的朋友作为一个数组返回。
4-定义一个非静态方法,返回一个人最老的朋友。
5-定义一个非静态方法来返回朋友的平均年龄。
6-定义一个方法 compareTo ,该方法接受一个人对象 p 作为参数来比较 p 的年龄和这个对象的年龄。(即,根据比较返回值 >0、=0 或 <0)
这是我不明白的问题的第二部分
1-定义一个非静态方法 addFriend 来向一个人添加朋友。请注意:
一个人只能在好友列表中添加一次。提示:使用 equals 方法检查我们要添加的人是否已经添加到列表中
一个人不能成为自己的朋友。提示:使用equals方法检查我们要添加的人是否与人相同
2-定义非静态方法isFriend,查看给定的人是否是该对象的朋友。
3-定义一个静态方法commonFriends,它以2个人对象为参数,并在一个ArrayList中返回这两个人的共同朋友。
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package person1;
import java.util.ArrayList;
public class Person1 {
private String Name;
private int Age;
private ArrayList<Person1>Friends=new ArrayList();
public String getName(){
return Name;
}
public String toString(){
String st="";
String x="";
st= Name+","+Age;
for(int i=0;i<Friends.size();i++)
x+=Friends.get(0).getName();
return st+","+x;
}
public int getFriends(){
return Friends.size();
}
public Person1 OldestFriends(){
int maxIndex=0;
for(int i=0;i<Friends.size();i++){
if(Friends.get(maxIndex).getAge())
maxIndex++;
}
return Friends.get(maxIndex);
}
public int compareTo(Person1 p) {
return (this.Age)-(p.Age);
}
public boolean equals(Person1 p) {
Person1 P= new Person1();
if(this.Name==P.Name&&Age == P.Age ){
// return ( Name.equals(P.name) && Age == P.Age );
//both objects have same Name
return true;
} else {
//both objects have different Name
return false;
}
}
public void addFriend(){
Friends = new ArrayList<Person1>();
}
}