Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java: Print elements of User defined Classes using ArrayList

When I try to run the code I don’t get 101,102,103 as output rather I get memory addresses of each value, I want to print the values 101,102,103 using "user defined class" pt_5_Employee as a parameter to the Array List . I tried using both for-loop and for-each-loop, but it dosen’t seem to be working. Will be grateful to any help to fix this problem 🙂 .

CODE:

    public class pt_5_employee {
        private int empId;
        public pt_5_employee(int empId) {
            this.empId=empId;
        }
        public static void main(String[] args) {
            ArrayList<pt_5_employee> x = new ArrayList<pt_5_employee>();
            x.add(new pt_5_employee(101));
            x.add(new pt_5_employee(102));
            x.add(new pt_5_employee(103));
            
            for(pt_5_employee X:x) {
                System.out.println(X);
            }
            
            System.out.println("-------\n");
            
            for(int i=0;i<x.size();i++) {
                System.out.println(x.get(i));
            }
            
        }
    }

Output which I’m getting:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Lists.pt_5_employee@6f2b958e
Lists.pt_5_employee@5e91993f
Lists.pt_5_employee@1c4af82c
-------

Lists.pt_5_employee@6f2b958e
Lists.pt_5_employee@5e91993f
Lists.pt_5_employee@1c4af82c

>Solution :

x. Get (i) gets an object, that is, pt_ 5_ If the employee instance is printed directly, it must be an object address, so you need to change x.get (i) to x.get (i). empId to print the results you want.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading