Reputation: 261
I want to know if there's a way to run a method of inside an element of an Arraylist but I don't want to do it with get because it actually changes fields of the element
thanks benny.
Upvotes: 4
Views: 1813
Reputation: 299058
Just to make everything even more clear than all the comments did:
public class ReferenceTester {
public static void main(final String[] args) {
final String original = "The One and only one";
final List<String> list = new ArrayList<String>();
list.add(original);
final String copy = list.get(0);
if (original == copy) {
System.out.println("Whoops, these are actually two references to the same object.");
} else {
System.out.println("References to a different objects? A copy?");
}
}
}
Run this class and see what it prints.
Upvotes: 2
Reputation: 421100
You don't want to do it with get
as in yourList.get(5).someMethod()
?
The get
method will not "extract" the element it returns, it will only return a copy of the reference. Getting + removing is the implementaiton of remove
.
So, unless you have overridden the get
method it will not modify the list.
Update and clarification:
List<String> list = new ArrayList<String>();
list.add(myObject); // add a reference to myObject in the list
// (remember, you can't pass around objects in java)
list.get(0).someMethod(); // get a copy of that reference and call someMethod()
Upvotes: 4