-1
new ArrayList<Integer>().addAll(Arrays.asList(4,5,6,7));

I could write:

ArrayList<Integer> my_array = new ArrayList<Integer>().addAll(Arrays.asList(4,5,6,7));

How can i access the first array later in my code without creating a reference to it?

ERJAN
  • 23,696
  • 23
  • 72
  • 146
  • 1
    Have a look at [Understanding Class Members](https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html) and [Passing Information to a Method or a Constructor](https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html) – MadProgrammer Oct 14 '15 at 04:56
  • 2
    I don't understand your question. – Sotirios Delimanolis Oct 14 '15 at 04:57
  • If I understand it right, you can't! You have to create a reference. I'm pretty sure you can't do that in any language. Again, if I understand it right. – Jorge Campos Oct 14 '15 at 04:58
  • why you don't want to create reference to it? – Naman Gala Oct 14 '15 at 05:00
  • If you only have `new ArrayList().addAll(Arrays.asList(4,5,6,7));`, then you can't access this list. See the links provided by @MadProgrammer. – pzaenger Oct 14 '15 at 05:01

2 Answers2

3

In your first code, you are just creating an object. And in the second piece of code, you are creating an object and putting it into a variable.

Let's have an analogy here, imagine that objects are like balloons, and the variables are like kids holding the balloons. In your first code, you create a balloon and "Let it go". And it flies away. In the second code though, you create a kid and a balloon and you told the kid to hold it. Now you can ask the kid for the balloon and you can access it.

So long story short, You cannot access the List in the first code.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
1

If you don't create a reference, you won't be able to access it. No exceptions that I am aware of.

I suppose you could push that new object into another ArrayList and then use .get() to access it again. No point to that unless you want a list of lists.

dainsleif
  • 81
  • 1
  • 8