如何从java中的链表中删除对象?
发布时间:2020-12-15 02:07:16 所属栏目:Java 来源:网络整理
导读:我的代码有一个问题,我做了一个示例程序来显示链接列表中的emp详细信息,现在我尝试删除特定条目时的问题意味着它不起作用,我希望我的代码中有一些错误你能建议怎么做吗? import java.util.*;class EmpDedup { int record; String fprint; int fid; EmpDedup
我的代码有一个问题,我做了一个示例程序来显示链接列表中的emp详细信息,现在我尝试删除特定条目时的问题意味着它不起作用,我希望我的代码中有一些错误你能建议怎么做吗?
import java.util.*; class EmpDedup { int record; String fprint; int fid; EmpDedup(int record,String fprint,int fid) { this.record = record; this.fprint = fprint; this.fid = fid; } public int getRecord() { return record; } public String getFprint() { return fprint; } public int getFid() { return fid; } public static void main(String[] args) { int count = 0; LinkedList<EmpDedup> list = new LinkedList<EmpDedup>(); list.add(new EmpDedup(101,"entry1",20)); list.add(new EmpDedup(102,"entry2",30)); list.add(new EmpDedup(103,"entry3",40)); list.add(new EmpDedup(104,"entry4",50)); Scanner input = new Scanner(System.in); System.out.print("Enter record no to display: "); int rec = input.nextInt(); for (EmpDedup data : list) { if (data.getRecord() == rec) { System.out.println(data.getRecord() + "t" + data.getFprint() + "t" + data.getFid() + "t"); count++; } } System.out.println("The size of an linkedlist is: t" + list.size()); System.out.println("The number of available record is :" + count); System.out.println("The size of an linkedlist is: t" + list.size()); Scanner input1 = new Scanner(System.in); System.out.print("Enter record no to delete: ");// here i try to delete a particular record int rec1 = input1.nextInt(); for (EmpDedup data : list) { if (data.getRecord() == rec1) { // System.out.println(data.getRecord()+"t"+data.getFprint()+"t"+data.getFid()+"t"); list.remove(data); // problem is here count++; } } } } 解决方法
在迭代它们时,你不能在列表中操作(添加,删除……项目).你必须使用迭代器
for(Iterator<EmpDedup> iter = list.iterator(); iter.hasNext();) { EmpDedup data = iter.next(); if (data.getRecord() == rec1) { iter.remove(); } } 见http://docs.oracle.com/javase/6/docs/api/java/util/Iterator.html (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |