-1

For example, I have a class, let's say,

public class Foo {
   private List<Object> dummyList;

   public void getDummyList() {
      return this dummyList;
   }  
}

I have a statement like below,

List<Object> realList = Foo.getDummyList();

Now, if I add item into realList, Foo's dummyList will also have this item. Is this called object reference? If not, what is the reason beside Java? It will be great if you can provide some tutorial?

FullStackDeveloper
  • 910
  • 1
  • 16
  • 40
  • 3
    `Is this called object reference?` - Yes, you are retriving a reference to you `dummyList` and adding to that exact list after that. You can google `Java reference types` – Timur Umerov Jun 20 '21 at 22:16
  • 3
    You can't access a non static method like that. – Sodrul Amin Shaon Jun 20 '21 at 22:16
  • 3
    Side note: In addition to @SodrulAminShaon's good point, if you use this code, and then try to add an item to the list, you will throw a NullPointerException because we don't see where the list variable has been assigned a viable List reference yet. Best to show *real* functioning code, if only to avoid the "nails on the chalkboard" distraction that bad code can give us. – Hovercraft Full Of Eels Jun 20 '21 at 22:17
  • Side note 2: if you want a getter that returns a protected list, one that does not allow addition or removal of items, then have your `getDummyList()` method return `Collections.unmodifiableList(dummyList);` This uses a static utility method from the `java.util.Collections` class. – Hovercraft Full Of Eels Jun 20 '21 at 22:33
  • Does this answer your question? [Is Java "pass-by-reference" or "pass-by-value"?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – Progman Jun 20 '21 at 22:33
  • 1
    Neither dummyList nor realList **are** actual lists. Both are **references** to the same actual list (or null, here, since you showed no code to actually create a list). Variables are not objects. – iggy Jun 20 '21 at 22:38

1 Answers1

0

First of all you need to initialize the list, but yes it's a reference to the list. These are two references to the same list. Changing one will affect the other, that's the beauty of java. If you don't want two references you will have to create a new list and move all values over to it.

Kallinn110
  • 29
  • 4