简体   繁体   中英

How to iterate Class Object from an ArrayList iterator

public class EmpArray {

    private int id;
    private String name,address;

    EmpArray(int id, String name, String addr)
    {
        this.id = id;
        this.name = name;
        address = addr;
    }
    int getId()
    {
        return id;
    }
    void display()
    {
        System.out.println("Employee details are ---");
        System.out.println("Id - "+id);
        System.out.println("Name - "+name);
        System.out.println("Address - "+address);
    }
}

In the main(), I have created an ArrayList to store EmpArray Class Objects My intention here, is to not store duplicate Id..

import java.util.*;
import java.io.*;
public class EmpArrayList {

    /**
     * @param args
     * @throws IOException 
     * @throws NumberFormatException 
     */
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String name,address;
        int id;

        //Create ArrayList
        ArrayList<EmpArray> arl = new ArrayList<EmpArray>();

        //Attach iterator to ArraList to check if Id is already added!!
        Iterator it = arl.iterator();

        enter:
        {
            for(int i =0 ; i < 3; i++)
            {

                System.out.println("Enter Id:");
                id = Integer.parseInt(br.readLine());

                while(it.hasNext())
                {

                    EmpArray temp = (EmpArray) (it.next());

                    if(id == temp.getId())
                    {
                        System.out.println("Id already exists! Add another Id : ");
                        break enter;
                    }   
                }

                System.out.println("Enter Name:");
                name = br.readLine();

                System.out.println("Enter Address:");
                address = br.readLine();

                //Create an object of EmpArray Class
                EmpArray e = new EmpArray(id,name,address);
                //Add this EmpArray object to the ArrayList
                arl.add(e);
            }
        }
        //Now display all the elements stored in the ArrayList
        /*for(int i=0 ; i< 3; i++)
        {
            EmpArray ea = arl.get(i);
            ea.display();
        }*/

        //Get Id from the user and display only that employee's details
        System.out.println("Enter Id whose details are required? : ");
        int searchId = Integer.parseInt(br.readLine());
        boolean isIdAvailable = false;

        for(int i = 0; i < 3 ; i++)

        {
            EmpArray ea = arl.get(i);
            if(searchId == ea.getId())
            {
                ea.display();
                isIdAvailable = true;
                break;
            }
        }
        if(!isIdAvailable)
            System.out.println("Employee details are not available");
    }
}

I get an exception when I try to enter the Id the second time. Exception is at it.next() Exception is Concurrent Modification Exception Can someone please help as to why I have this exception?

you are iterating over array list ArrayList<EmpArray> arl and after that you are changing it's state arl.add(e); modifying it by adding value into it that's why ConcurrentModificationException came. If possible use another array list to add modified content into it.

But, you have issue with duplicate contents why not you use Set and Comparator or Comparable .

Instead of creating your own duplicate-safety mechanism, consider implementing hashCode and .equals() in your custom object. This way you can comfortably use .contains on the ArrayList to avoid duplicates.

Here's a nice document about such implementation: http://www.programcreek.com/2011/07/java-equals-and-hashcode-contract/

Assuming that now you know why you are getting that exception, a simple way to do away with it is to not use the iterator, but use simple for loop instead.

// Attach iterator to ArraList to check if Id is already added!!
    // Iterator it = arl.iterator();

    enter: {
        for (int i = 0; i < 3; i++) {

            System.out.println("Enter Id:");
            id = Integer.parseInt(br.readLine());

            for (i = 0; i < arl.size(); i++) {

                EmpArray temp = (EmpArray) (arl.get(i));

                if (id == temp.getId()) {
                    System.out
                            .println("Id already exists! Add another Id : ");
                    break enter;
                }
            }

            System.out.println("Enter Name:");
            name = br.readLine();

            System.out.println("Enter Address:");
            address = br.readLine();

            // Create an object of EmpArray Class
            EmpArray e = new EmpArray(id, name, address);
            // Add this EmpArray object to the ArrayList
            arl.add(e);
        }
    }

Thank you everyone for your inputs! I now understand why I had such an exception.

I also understand that Sets are in place to avoid duplicates but my intention was to use an ArrayList and handle duplicates in it! I am now not using an iterator but a simple loop!

Thank you again.

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