如何删除链接列表中的对象。我有一个带有studentId和studentName的班级帐户。我在列表中输入了对象,但是当我尝试删除对象时我不知道该怎么做。因为每次从列表中间删除元素时,它都会被组织起来,这意味着索引会改变。因此,如何获取studentId属性并删除链表中的对象。
示例:
LinkedList: Account{studentId = 1, studentName = nome1} = index = 0 ,
LinkedList: Account{studentId = 2, studentName = nome2} = index = 1 ,
LinkedList: Account{studentId = 3, studentName = nome3} = index = 2.
我想要的是让用户插入他要删除的studentId,我可以执行一个代码来搜索和删除该对象。
public Account{
private int studentID;
private String StudentName;
}
public static void main(String[] args){
int accountNumber;
LinkedList<Account> linkedAccount = new LinkedList<>();
Account obj1;
System.out.println("Type the acc number: ");
accountNumber = in.nextInt();
obj1 = linkedAccount.remove(accountNumber);
System.out.println("The " + obj1 + " has been deleted");
}
每次我从中间删除对象时,它都会更改linkedList的索引。重新排列。所以我不知道该怎么办,您能帮我吗?
答案 0 :(得分:2)
如果您不需要保留对要删除的对象的引用,则可以
linkedAccount.removeIf(acc -> acc.getStudentID() == accountNumber);
如果要保留对要删除的元素的引用,可以
for (Account acc : linkedAccount) {
if (acc.getStudentID() == accountNumber) {
obj1 = acc;
linkedAccount.remove(acc);
break;
}
}
// OR
for (int i = 0; i < linkedAccount.size(); i++) {
if (linkedAccount.get(i).getStudentID() == accountNumber) {
obj1 = linkedAccount.remove(i);
break;
}
}
请注意,在大多数情况下,基本上ArrayList
就足够了When to use LinkedList over ArrayList in Java?
答案 1 :(得分:1)
当前,您使用accountNumber
作为不正确的索引,而是遍历列表并找到对象的索引,然后删除:
for (int i = 0; i < linkedAccount.size(); i++) {
if (linkedAccount.get(i).getStudentID() == accountNumber) {
obj1 = linkedAccount.remove(i);
break;
}
}
此外,为什么要使用LinkedList
而不是ArrayList
?后者几乎总是有利的。
答案 2 :(得分:1)
我认为最好的选择是按StudentID在列表中搜索该帐户,然后将其删除。
public Account{
private int studentID;
private String StudentName;
public int getStudentID() {
return this.studentID;
}
}
public static void main(String[] args){
int accountNumber;
LinkedList<Account> linkedAccount = new LinkedList<>();
Account obj1;
System.out.println("Type the acc number: ");
accountNumber = in.nextInt();
for (int i = 0; i < linkedAccount.size(); i++) {
if (accountNumber == linkedAccount.get(i).getStudentID()) {
System.out.println("The student " + linkedAccount.get(i).getStudentID() + " has been deleted");
linkedAccount.remove(i);
break; // This is to exit for loop, but if you want to delete every instance in the list with this ID you can skip this break
}
}
}