Run method in Arraylist element in java

I want to know if there is a way to run a method inside an Arraylist element but I don't want to do this with get, because it actually modifies the fields of the element

thanks Benny.

+4
source share
2 answers

Just to make everything more understandable than all comments:

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.

+2
source

You do not want to do this with get , as in yourList.get(5).someMethod() ?

The get method will not "retrieve" the returned element, it will only return a copy of the link. Getting + removal is the implementation of remove .

So, if you do not override 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() 
+4
source

Source: https://habr.com/ru/post/1312836/


All Articles