gpt4 book ai didi

java - 如何从对象的 LinkedList 以及所有这些对象的 LinkedList 中删除对象?

转载 作者:行者123 更新时间:2023-12-02 03:49:12 24 4
gpt4 key购买 nike

我一直在尝试编写一种方法,不仅可以从 LinkedList(allUsers) 中删除对象(User),还可以从所有用户拥有的单个 LinkedList 中删除。谁能向我解释为什么这是错误的?我已经包含了相关方法和 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));
}
}

最佳答案

让 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
}
}
}

关于java - 如何从对象的 LinkedList 以及所有这些对象的 LinkedList 中删除对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36023413/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com