0

how can I get acces to a field of an object in an ArrayList, when the object extends the type I wrote in the ArrayList generics ?

Heres the code:

ArrayList<ObjectA> objA = new ArrayList()<>;
objA.add( new ObjectA() );  
objA.add( new ObjectAB() ); // ObjectAB extends ObjectA

now I would like to change the variablein ObjectAB, stored in the list

( only ObjectAB has this field, not ObjectA )

2
  • What do you mean by only ObjectAB has this field, not ObjectA? Commented Dec 5, 2013 at 7:45
  • 1
    @Masud He added some more fields in the extended class ObjectAB; and he is trying to access them. Ofcourse reference of type ObjectA cannot show the newly added fields in its child class. Commented Dec 5, 2013 at 7:47

2 Answers 2

5

If I understand you correctly, you want to do something like this:

ArrayList<ObjectA> objA = new ArrayList()<>;
objA.add( new ObjectA() );  
objA.add( new ObjectAB() ); // ObjectAB extends ObjectA

ObjectAB ab = (ObjectAB) objA.get(1);
ab.setFieldFromAB("foo");

So you have to cast item from list objA to type ObjectAB. If you are not sure the cast will succeed you might want to do some checks first like

if(objA.get(1) instanceof ObjectAB) {
   ObjectAB ab = (ObjectAB) objA.get(1);
   ab.setFieldFromAB("foo");
} else {
   //doSomethingElse
}
Sign up to request clarification or add additional context in comments.

Comments

1

When you retrieve back objects from the ArrayList, you will get Objects of type ObjectA only. Because ArrayList<T> is the list of T type objects.

ObjectA obj0 = objA.get(0);
ObjectA obj1 = objA.get(1);   // This you cannot get as the reference of ObjectAB

You need to explicitly downcast obj1 to ObjectAB

ObjectAB obj1B = (ObjectAB) obj1;

However if you really require explicit downcasting, then you are defeating the very purpose of the Generics - type safety. For sure there would be some better ways.

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.