1

如何删除 Linkedlist 中的对象。我有一个带有 studentId 和 studentName 的班级帐户。我在列表中输入了对象,但是当我尝试删除时,我不知道该怎么做。因为每次从列表中间删除一个元素时,它都会被组织起来,这意味着索引会发生变化。那么如何获取 studentId 属性并删除linkedList中的对象。

样本:

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 的索引。重新排列。所以我不知道该怎么做你能帮我吗?

4

3 回答 3

2
  1. 如果您不需要保留对您删除的对象的引用,您可以

    linkedAccount.removeIf(acc -> acc.getStudentID() == accountNumber);
    
  2. 如果您想保留对您删除的元素的引用,您可以

    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;
        }
    }
    
  3. 请注意,在大多数情况下,基本上一个ArrayList就足够了 何时在 Java 中使用 LinkedList 而不是 ArrayList?

于 2019-01-08T21:31:41.990 回答
1

目前,您使用accountNumber的索引不正确,而是遍历列表并找到对象的索引,然后删除:

for (int i = 0; i < linkedAccount.size(); i++) {
     if (linkedAccount.get(i).getStudentID() == accountNumber) {
         obj1 = linkedAccount.remove(i);
         break;
     }
}

此外,您为什么使用 aLinkedList而不是 a ArrayList?后者几乎总是有利的。

于 2019-01-08T21:26:58.353 回答
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
      }
   }
}
于 2019-01-08T21:32:36.253 回答