I’m looking at some code and I want to make sure I understand whether some changes made to objects are actually made to those objects or copies of those objects.
Here’s a sample:
for(int i = 0; i < myList.size(); i++)
{
DataObject myItem = (DataObject)myList.get(i);
myItem.setString("someKey", "someValue");
}
myList is a List of DataObjects, so I’m not sure what the purpose was of casting the item to a DataObject after calling the get() method on the list. But I wonder how this is handled when it is compiled — will the cast create a new object, and then the setString() method will be called on that new object and not affect the object in the list? Or is myItem referencing the actual item in the list?
Thanks.
It’s still a reference to the item in the list after casting. A copy is not created.
List returns a type of the Object class, so that it can be used for any type of
Object(as all classes extendObject). In order to call setString though, you need to to cast the reference type to something more specific, so that the compiler knows what kind of object you are calling it on.Using generics e.g.
Listwith your list to specify the types will mean you don’t have to cast, but may not be suitable if you can’t control the List creation or don’t know or want to restrict what types of Objects may be in it.