나는 arraylist에 객체를 추가하는 친구를 추가하는 간단한 sch 프로그램을 수행하고 있습니다. 나는 모든 것을 따라 갔지만 나의 방법 befriend()는 효과가없는 것 같습니다. 수동으로 주에서 .add()를 사용하여 테스트하면 작동합니다. 내가 어디에서 잘못하고 있니?Arraylist 님이 자바를 추가하지 않았습니다
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 방법은 당신이 생각하는 일을하지 않는 당신에게 말할 수있는 친구를 추가 계속 - 디스플레이의 의견과는
이게 뭐야 :'new ArrayList (Arrays.asList (p.getFriendList()));'? 왜 목록을 배열로 다시 목록으로 변환합니까? 그리고 코드를 표시하지는 않았지만 이는 사본을 생성하므로 원본에 대한 작업은 사본에 아무런 영향을 미치지 않습니다. –
두 가지 : 1) 'ArrayList anotherList = new ArrayList (Arrays.asList (p.getFriendList()))' 끔찍해. 이런 종류의 코드를 작성하지 마십시오. 2) 요점은 친구를 서로 중복 제거하려는 것입니다. List 대신 Set을 사용하면 매우 쉽습니다. :-) –
MageXellos