Home > Blockchain >  Java: Print elements of User defined Classes using ArrayList
Java: Print elements of User defined Classes using ArrayList

Time:09-14

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:

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

CodePudding user response:

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.

  • Related