0
List <Person> pers = new ArrayList<Person>();

pers.add(new Women("something1"));
pers.add(new Women("something2"));

pers.add(new Men("something1"));
pers.add(new Men("something2"));

System.out.println(pers); // prints everything

The classes Women and Men extend Person. After I store the data in my list how do I print only the Women or only the Men? Also how do I access attributes from the Women and Men?

With 2 lists works fine but I'm having trouble when I only have to use one list.

2
  • You could try using instanceof operator, but that usually means that your design is flawed. Why do you want to create only one list of peers? What is wrong with solution using two separate lists? Commented Oct 31, 2015 at 20:20
  • Well, if you need to distinguish men from women, you shouldn't store them in the same list. Commented Oct 31, 2015 at 20:21

2 Answers 2

4

Use the instanceof keyword.

for(Person person : pers){
    if(person instanceof Women){
        System.out.println("I am a woman");
        int height = person.getHeight();
    }
    else if(person instanceof Men){
        System.out.println("I am a Man");
        int weight = person.getWeight();
    }
}

Once you know what type of object the person is, you can call any public variables/getters/setters on that object.

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

1 Comment

Thanks , that helped. :)
0

Object.getClass() will return the type of the object

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.