英文:
Remove the duplicates from a list and move the the other duplicate on top of the list
问题
我正在尝试测试一个代码,如果我将新元素添加到列表中,它会检测相似的元素并删除其中一个重复的元素,但会将另一个移到列表的开头。
public class MemberList {
List<String> members;
public MemberList() {
this.members = new ArrayList<String>();
}
//这部分是我试图修复的!!!
public void addMember(String FirstName, String LastName) {
members.add(0, FirstName + " " + LastName);
}
}
英文:
I'm trying to test a code that if I add new element to the list it detects the similar element and remove one of the duplicates but move the other one to the beginning of the list.
public class MemberList {
List<String> members;
public MemberList() {
this.members = new ArrayList<String>();
}
//This is the part I'm trying to fix!!!
public void addMember(String FirstName, String LastName) {
members.add(0, FirstName + " " + LastName);
}
}
答案1
得分: 1
替代ArrayList,我认为你应该使用LinkedHashSet,因为在你的集合中不允许重复元素。而且LinkedHashSet会保留插入顺序,所以当你检测到重复时,可以删除旧元素并将新元素插入集合。
public class MemberList {
Set<String> members;
public MemberList() {
this.members = new LinkedHashSet<String>();
}
public void addMember(String FirstName, String LastName) {
String key = FirstName + " " + LastName;
if (members.contains(key)) {
members.remove(key);
}
members.add(key); // 总是添加到末尾
}
}
请记住,LinkedHashSet会将新元素始终添加到末尾,因此在开始的情况下,你需要获取最后一个元素。
英文:
Instead of ArrayList, I think you should use LinkedHashSet as no duplicated elements are allowed in your collection. And LinkedHashSet will reserve insertion order so when you detect a duplicate, you can remove old one and insert new one to set.
public class MemberList {
Set<String> members;
public MemberList() {
this.members = new LinkedHashSet<String>();
}
public void addMember(String FirstName, String LastName) {
String key = FirstName + " " + LastName;
if (members.contains(key)) {
members.remove(key);
}
members.add(key); // Always add to tail
}
}
Remember LinkedHashSet will always add new elements to the tail, so you need to get last element for your beginning case.
答案2
得分: 0
以下是完成任务的方法(由于效率原因不太优选):
public void addMember(String FirstName, String LastName) {
String name = FirstName + " " + LastName;
if (members.contains(name)) {
members.remove(name);
members.add(0, name);
} else {
members.add(name);
}
}
英文:
List way to accomplish the task (not preferred due to efficiency):
public void addMember(String FirstName, String LastName) {
String name = FirstName+" "+LastName;
if(members.contains(name)) { // checks if the list contains name value
members.remove(name); // removes the first occurrence of the name from the list
members.add(0,name); // adds the name to 0th position of the list
} else {
members.add(name); // if name not found in list, appends the value to the list
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论