java list 删除对象,如何从java中的链表中删除一个对象?

i have one problem with my code ,i did a sample program to display the emp details from a linked list,now the problem when i trying to delete a particular entry means it doesn't work,i hope i did some mistake in my code could you suggest how to do that?

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 list = new LinkedList();

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++;

}

}

}

}

解决方案

you cannot operate in lists (add, remove... items) while you iterate on them. You have to use an Iterator

for(Iterator iter = list.iterator(); iter.hasNext();) {

EmpDedup data = iter.next();

if (data.getRecord() == rec1) {

iter.remove();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值