Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - ArrayList and creating an object

Tags:

java

arraylist

The header question is a little bit tricky, so here's my problem:

1- I created an object y of an arraylist and I assigned it as a reference variable, so far so good.

ArrayList<String> y = new ArrayList<String>();

2- Here I added an element to the array:

y.add("Hello"); y.add("GoodBye");

Now here's the part that I don't understand, now when I create a method that returns a String:

public String stringful(ArrayList<String> list)

Now when I try to get the size() of the array, I use list.size() but why? Isn't y the original object and I should use y.size() although it doesn't work so that's why I'm here. Thanks

like image 315
Imonar Smith Avatar asked Feb 09 '26 20:02

Imonar Smith


2 Answers

With this method header:

public String stringful(ArrayList<String> list)

You're declaring that this method will use an object, of type ArrayList<String> called list. Because you declare y locally, the other method has no idea that even exists. Reference to y from that method won't compile, assuming of course that it is a local variable.

Pointers in Java

When you create a new object, you use a pointer to that object. For example, when you declare:

ArrayList<String> y;

you're creating a pointer. When you add the code:

ArrayList<String> y = new ArrayList<String>();

This puts the pointer to a new ArrayList<String> object into the y variable. So when you pass y as a parameter into a method, you're passing a pointer to the object that y also points to, not the object iself. This is why your code works with list.size(). All it's doing is getting the size value of the exact same object, just with a different pointer.

Summary

In Summary, it actually is the same object. It's just different pointers, looking at that object.

like image 157
christopher Avatar answered Feb 12 '26 16:02

christopher


You are passing the reference to the ArrayList<String> y to method stringful to list reference variable and hence will use list.size(). y is unknown to that method unless y is an instance or class variable which is visible in that method. list is the local variable here which is used to pass the reference of y. This way you can pass a reference of any ArrayList<String> to that method and calculate its length. If you had used y.size() in that method (provided y is visible in that method), then you could have been able to calculate only the length of ArrayList<String> referenced by y.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!