1

In an ArrayList I have two different objects, Student and Employee. I want to iterate through them one by one. I am able to iterate through the list and use the Employee objects but not the Student objects.

I have the following code:

package javaCollections;

import java.util.ArrayList;
import java.util.Iterator;

class Employee {

    @Override
    public String toString() {
        return "employee [name=" + name + ", age=" + age + "]";
    }

    public String name;
    public int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    Employee(String name, int age) {
        this.age = age;
        this.name = name;
    }

}

class Student {

    @Override
    public String toString() {
        return "student [stud_name=" + stud_name + ", rollNumber=" + rollNumber
                + "]";
    }

    String stud_name;
    int rollNumber;

    public Student(String stud_name, int rollNumber) {
        super();
        this.stud_name = stud_name;
        this.rollNumber = rollNumber;
    }

    public String getStud_name() {
        return stud_name;
    }

    public void setStud_name(String stud_name) {
        this.stud_name = stud_name;
    }

    public int getRollNumber() {
        return rollNumber;
    }

    public void setRollNumber(int rollNumber) {
        this.rollNumber = rollNumber;
    }
}

public class Arraylist {

    ArrayList<Object> emparray;

    public void addemp() {
        Employee emp = new Employee("abc", 12);
        emparray = new ArrayList<Object>();
        emparray.add(emp);
        Employee emp1 = new Employee("def", 12);
        emparray.add(emp1);

        Student std = new Student("efg", 123);
        Student std1 = new Student("xyz", 123);
        emparray.add(std);
        emparray.add(std1);

    }

    public void iterateemp() {
        /*
         * Iterator<Object> itr=emparray.iterator();
         * 
         * while(itr.hasNext()) { System.out.println(itr.next()); }
         */

        for (Object e : emparray) {
            System.out.println(((Employee) e).getAge());
            System.out.println(((Employee) e).getName());
        }
    }

    public static void main(String[] args) {
        Arraylist al = new arraylist();
        al.addemp();
        al.iterateemp();
    }

}

can someone please help me on this?

3
  • 1
    You could create a common class which both student and employee inherit from. Make the type of the ArrayList only contain this specific class. Commented Oct 8, 2015 at 14:59
  • 1
    You should try to avoid using instanceof if possible, You can avoid it here because these are your classes. You want a common interface or base class. Commented Oct 8, 2015 at 15:03
  • You should capitalize all class names (i.e. Student, Employee and Arraylist). You should also avoid giving a class a name that could be confused with another class, especially a core JAVA class (i.e. ArrayList and arraylist). These are just general best practices for writing professional code. Commented Oct 8, 2015 at 15:21

3 Answers 3

6

What you need to do is check the instance of the object.

for (Object e : emparray) {
        if(e instanceof employee) {
            System.out.println(((employee) e).getAge());
            System.out.println(((employee) e).getName());
        } else if(e instanceof student) {
            // do something else
        }
    }
}

IMO this is a bad design.

Sign up to request clarification or add additional context in comments.

1 Comment

If you this this is the correct answer then please mark it as the answer to help other readers ... meta.stackexchange.com/questions/5234/…
4

The best practice is to create common base called Person that has shared fields like name. Then you can replace Object with Person in the loop.

import java.util.ArrayList;
import java.util.Iterator;



interface Person{

     public String getName();
     public void setName(String name);
}

class employee implements Person{


    @Override
    public String toString() {
        return "employee [name=" + name + ", age=" + age + "]";
    }

    public String name;
    public int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    employee(String name, int age) {
        this.age = age;
        this.name = name;
    }

}

class student implements Person{

    @Override
    public String toString() {
        return "student [stud_name=" + name + ", rollNumber=" + rollNumber
                + "]";
    }

    String name;
    int rollNumber;

    public student(String stud_name, int rollNumber) {
        super();
        this.name = stud_name;
        this.rollNumber = rollNumber;
    }


    public int getRollNumber() {
        return rollNumber;
    }

    public void setRollNumber(int rollNumber) {
        this.rollNumber = rollNumber;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public void setName(String name) {
        this.name=name;
    }
}

public class arraylist {

    ArrayList<Person> emparray;

    public void addemp() {
        employee emp = new employee("abc", 12);
        emparray = new ArrayList<Person>();
        emparray.add(emp);
        employee emp1 = new employee("def", 12);
        emparray.add(emp1);

        student std = new student("efg", 123);
        student std1 = new student("xyz", 123);
        emparray.add(std);
        emparray.add(std1);

    }

    public void iterateemp() {
        for (Person e : emparray) {
            if (e instanceof employee) {
                System.out.println(((employee) e).getAge());    
            }else{
               /// do for student   
            }
            System.out.println(e.getName());
        }
    }

    public static void main(String[] args) {
        arraylist al = new arraylist();
        al.addemp();
        al.iterateemp();
    }

}

1 Comment

Correct and an interesting pattern in this case is the Visitor. You can have an accept(PersonVisitor<Foo>) method and the visitor contains a method for Employee and another for Student. This allows you to manipulate the Person and make sure you don't get a nasty ClassCastException because you forget an instanceof somewhere. Overkill in this example but worth knowing about.
3
for (Object e : emparray) {
        if(e instanceof employee) {
            System.out.println(((employee) e).getAge());
            System.out.println(((employee) e).getName());
        } else if(e instanceof student) {
            System.out.println(((student) e).getRollNumber());
            System.out.println(((student) e).getStud_name());
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.