我正在做一個簡單的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