我正在做一个简单的sch程序来添加朋友,即将对象添加到arraylist中。我遵循了一切,但我的方法befriend()似乎并不奏效。 当我手动测试使用.add()在主,它的作品。我在哪里做错了?Arraylist not adding java
import java.util.*;
public class NetworkFriends {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Person me = new Person("Aloysius", 1);
ArrayList<Person> myList = new ArrayList<Person>(Arrays.asList(me.getFriendList()));
Person p1 = new Person("Gorgon", 2);
Person p2 = new Person("Eddy", 3);
me.befriend(p1);
for(Person i : myList) {
System.out.println("Name: " + i.getName());
}
}
}
class Person
{
private int id;
private String name;
private ArrayList<Person> friendList;
private static int runningNum = 0;
private static int friendsLimit = 5;
private String degree;
private int degreeNum;
/* Constructor - 1 param */
public Person(String name, int degreeNum)
{
//Implement your code here..
//Initialize all necessary variable(s)
this.name = name;
friendList = new ArrayList<Person>(5);
this.degree = degree;
this.degreeNum = degreeNum;
}
public void befriend(Person p){
//Implement your code here..
ArrayList<Person> anotherList = new ArrayList<Person>(Arrays.asList(p.getFriendList()));
for(Person i : friendList) {
if(!isFriend(this) && friendList.size() < 5) {
friendList.add(p);
anotherList.add(this);
}
else if(!isFriend(this) && friendList.size() == 5) {
System.out.println("Friends limit reached");
}
else {
System.out.println("Already in friend list");
}
}
}
}
public boolean isFriend(Person p){
//Implement your code here..
boolean isItAFriend = true;
for(Person i : friendList) {
if(friendList.contains(p)) {
isItAFriend = true;
}
else {
isItAFriend = false;
}
}
return isItAFriend;
}
我可以告诉你,你isFriend方法是不是做你认为它是。但是由于这看起来像是家庭作业,我会强烈建议您花几分钟时间熟悉使用调试器并使用它,因为它可以快速回答您的问题。 https://www.youtube.com/watch?v=9gAjIQc4bPU –
这是什么:'new ArrayList(Arrays.asList(p.getFriendList()));'?你为什么要再次将一个列表变成一个列表成为一个列表?并且(虽然您没有显示代码)会创建副本,因此原件上的操作不会影响副本。 –
两件事:1)'ArrayList anotherList = new ArrayList (Arrays.asList(p.getFriendList()));'是可怕的。不要写这种代码。 2)关键点是你想互相去重复朋友。使用Set而不是List将使其变得非常容易。 :-) –
MageXellos