我一直在尝试编写一种方法,不仅可以从LinkedList(allUsers)中删除对象(User),还可以从所有用户拥有的各个LinkedLists中删除。任何人都可以向我解释为什么这是错的?我已经包含了有问题的方法和User类。
public void removeUser(User u){
//curr equal to front of users list
Node curr=allUsers.getFront();
//loop to remove friend from FriendsList
while(!curr.getNext().getData().equals(u)||curr.getNext()!=null){
curr=curr.getNext();
}
if(curr.getNext()!=null)
allUsers.remove(allUsers.indexOf(curr.getNext().getData()));
//loop to run through allUsers
curr=allUsers.getFront();
while(curr!=null){
if(curr.getData().getFriends().size()!=0){
//run through friends LinkedLists of each user
Node curr2=curr.getData().getFriends().getFront();
while(curr2!=null){
if(curr2.getData().equals(u))
curr2.getData().removeFriend(u);
curr2=curr2.getNext();
}
}
curr=curr.getNext();
}
}
用户类:
public class User{
private String name;
private String location;
private int birthYear;
private LinkedList friends;
public User(String n, String l, int b){
name=n;
location=l;
birthYear=b;
friends=new LinkedList();
}
public String getName(){return name;}
public String getLocation(){return location;}
public int getBirthYear(){return birthYear;}
public boolean equals(User u){
if(this.getName().equals(u.getName())&&this.getLocation().equals(u.getLocation())&&this.getBirthYear()==u.getBirthYear())
return true;
else
return false;
}
public LinkedList getFriends(){return friends;}
public int getNumFriends(){return friends.size();}
public String toString(){
return name+" from "+location;
}
public void addFriend(User u){friends.addToEnd(u);}
public void removeFriend(User u){
if(friends.indexOf(u)!=-1)
friends.remove(friends.indexOf(u));
}
}
答案 0 :(得分:2)
让LinkedList为您完成工作:
public void removeUser(User u){
while (allUsers.remove(u)) {
// this loops continue until there are no more entries of user in allUsers (as defined by the User.equals() method)
}
// now remove this user from all the remaining user's friends list
for (User user : allUsers) {
while (user.getFriends().remove(u)) {
// remove all occurances
}
}
}