简体   繁体   中英

How can i delete the record from employeelist?

I've been trying to delete the record from employeelist if name found from keyboard. how can i delete the data if the name matched? employeelist has all information including staff names, address,number etc. here is my code..

public static void main(String arg[])
{
Scanner kb = new Scanner(System.in);
ArrayList<StaffMember> employeelist = new ArrayList<StaffMember>();

Staff personnel = new Staff();
StaffMember rc = null;

for (int i=0; i<personnel.getSize(); i++)
{
  employeelist.add(personnel.getStaff(i));
 }


 boolean n = true;


for (int i=0; i<personnel.getSize(); i++)
{
 while(n)
 {
 System.out.print("Enter the name: ");
 String inLine = kb.nextLine();

 rc = employeelist.get(i);
 System.out.println(rc.name);

 if(rc.name.equals(inLine))
 {
    n = false;
 }
 else
 {
 employeelist.remove(i);

 }
 System.out.println(employeelist);

 }
 }      
 }
 }

If you want to delete the record for the name found from keyboard (Input from terminal) ,

You might try this :

 System.out.print("Enter the name: ");
 String inLine = kb.nextLine();

 for (int i=0; i<personnel.getSize(); i++)
 {
  rc = employeelist.get(i);
  System.out.println(rc.name);

  if(rc.name.equals(inLine))
  {
   employeelist.remove(i); 
   break; //
  }

 }   

Hope this helps.

Due to fail-fast property of list you can not modify list during irritating it. you will get " ConcurrentModificationException ". You can directly invoke list.remvoe() with overriding equals method of staff class.

If you want to modify list during irritating it , you need to use ListIterator which is fail-safe . You can do something like this.

public static void main(String[] args) {

    List<String> list = new ArrayList<String>();
    // adding Values in list
    list.add("Raghvendra");

    for (int i = 0; i < 5; i++) {
        list.add("Item" + i);

    }

    System.out.println(list);

    for (ListIterator<String> listIterator = list.listIterator(); listIterator
            .hasNext();) {
        String val = (String) listIterator.next();
        if (val.equals("Raghvendra"))
            listIterator.remove();

    }

    System.out.println(list);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM