I'm curious about the object reference in java let's say we have a Person object
Person object = new Person("Joe");
I put it in an ArrayList<Person>
ArrayList<Person> person_collection = new ArrayList<Person>();
person_collection.add(object);
I create a new collection of Person again, then copy the items of person_collection
ArrayList<Person> collection = new ArrayList<Person>(person_collection);
If I get the item from collection
Person p = collection.get(i);
Is p has a reference to person_collection ??
In this case, p contains in the initialization step at least all the elements of person_collection.
So when you directly iterate over this newly created collection, you will get the same pointed Person elements that the ones contains into the initial collection.
By the way, as Java never use the pass-by-reference but always the pass-by-value method, references themselves are not the same but that does not prevent them to point to the really same objects.
Yes, the Person "object" variable reference will be returned back in Person "p" variable .
person_collection and collection will be referencing 2 different collections containing the object pointed p.
Related
I've got a piece of code
list.add(new Person())
Since the Person object is missing it's naming part
Person p = new Person()
What kind of name does this person object get assigned to?
Is it important to know the name of the object?
How would I go about accessing this object's methods if it is added to the ArrayList without a name?
edit: name == reference. I know objects don't have names
p is not "the name of the object". p is a variable that happens to hold a reference to the Person object. Objects don't have names.
If you skip declaring the p variable and add the Person object directly to the ArrayList, the ArrayList still holds a reference to that object, so it doesn't matter whether you use list.add(new Person()) or list.add(p).
Either way you can retrieve the reference to the Person with list.get(index), and then execute any methods you wish.
I think, that the name of the Person-Object doens't matter.
You can simply access it with list.get(int number).
This will give you the refernce to the element at the position.
Hope I understood your question correctly and this helps you.
The name is only used by developers for reference, it's not actually needed at runtime.
To access your object you'd use:
List<Person> list = new ArrayList<Person>(); // Create the list
list.add(new Person()); // Add the person to the list
list.get(0); // Returns the person you added
If you want to get specific people from your list I'd suggestion using a HashMap and store their names as the keys.
I think you may be confusing the creation of an object with assigning a reference to that object. In you example p is a reference to the object Person that you have created. You have not named that object p, but have a reference called p to the object person.
To create a reference to the person object from list.add(new Person()) you simply do a
Person p = list.get(0)
You can access the object from its index in the List.
An object lives in JVM memory heap, and doesn't have such a thing as a name. It can be referenced by variables that can be lists or single elements. In the case of the list you can reference the object by accessing the list element by its index.
Please correct me if I am wrong, I just want some clarification that I'm understanding this right.
When you create an object in java you use the new keyword followed by the class type. Ex. new [someclassnamehere]();
Depending on your constructors you can pass arguments by supplying them in the parameter when you create the object.
I'm not sure if it would ever be useful to just have a line of code that creates a new object o by just using the new keyword, because nothing is actually holding the reference to that information. But it's correct it seems.
So you can create a variable that contains the reference to the new object you are creating by using type name.Such as: Employee someData; . But it has yet to actually reference an object, seeing as one hasn't been created yet. So by applying the above information discussed:
Employee someData = new Employee(name);
We now created an Employee object that contains some name of the employee. The new keyword created an instance of the class Employee, an object, in which the someData variable references that newly created object.
So now the someData variable can be said to reference the Employee object because it contains the address in memory of where the object is stored. This address will allow us to access the actual data of the object, in this case the name of the employee.
If I were to create an ArrayList that has the datatype Employee, I can store Employee objects in it. So I can add the someData variable to the arrayList as well as someData2,someData3,etc. (Just assuming they are all of the same type but contain different employee information).
So each of those variables contain references to these objects. The ArrayList object then contains references to these objects as well because the ArrayList elements contain these someData variables which reference the Employee Objects.
example:
ArrayList.get(1) -> someData -> reference variable(address) -> employee Object
ArrayList.get(2) -> someData2 -> reference variable(address) -> employee Object2
Pretty sure I got the idea down so far, but what slightly throws me off is when you actually don't create a reference variable.
So let's say you create a loop which creates an object(data is being read from some database,etc) and adds it to an ArrayList. In this loop you collect the data you want and use that to create an object, which is then directly added to an ArrayList.
Let's say it looks like this (combination of some pseudo code and actual code)
ArrayList<Employee> list = new ArrayList<Employee>();
// While data from the database still exist (while loop,etc)
// extract some sort of data from the database, such as their name and hours
// create an object of this information and store it in an ArrayList
list.add(new Employee(name, hours);
// end loop
For simplicity, let's said the loop ran 5 times so it created 5 objects.
This means it added 5 objects to the ArrayList List and the references to these objects are actually contained in the ArrayList elements. So to get the first object added to the ArrayList you would use list.get(1) (I'm pretty sure ArrayList start at 1 and not 0 for indexes), which returns the reference to that object.
EDIT: Please forgive me for my mistake here, I suppose I had a brainfart and got mixed up. I don't know why I thought ArrayList indexes worked like that for a second
Is this correct and standard way of creating objects through the use of a loop?
I'm not sure if it would ever be useful to just have a line of code that creates a new object o by just using the new keyword, because nothing is actually holding the reference to that information. But it's correct it seems.
Imagine that the constructor starts a new thread. No reference, but
new AmazingThread();
is fine in that case.
Well, this question is huge. And yes, creating objects like this is completely legit. You can think of ArrayList having it's own variable storing the reference.
I recently learned that you cannot initialize objects using an enhanced for loop in Java because of the way an enhanced for loop works by creating a 'dummy' object from the object and then performing whatever the code states using the dummy object
But this prompted me to attempt to change field variables inside objects using an enhanced for loop and surprisingly the code changed the field variables in the objects. Can anyone please explain to me how this works because to my understanding no change should occur to the objects for the same reason you can't initialize objects using the enhanced for loop. Clearly I have exposed a gap in my understanding here so can anyone help me out
In java the objects you see are not objects but in fact object references.
An object reference is just an reference to the object in RAM.
For example.
Person p1;
Person p2;
p1 = new Person(); // p1 now has an reference to an Person object
p2 = p1; // Now p2 and p1 point to the same object
Now, if we made a change to the p2's object, that change would be reflected to p1's object because they refer to the same object.
For example.
p2.setHeight(50);
p1.setHeight(90);
System.out.println(p2.getHeight());
The code snippet above would print out 90, not 50. Because first the object's height was set to 50, but then the objects height was set to 90(using some other object reference).
Going back to your question.
for(Person p : peopleArray)
{
// more code
}
In every cycle of the for loop, an object reference p is created and refers to the same object that an object reference in peopleArray refers to.
In an enhanced for loop you are allowed to modify objects, but you are not allowed to change the data structure you are iterating through. This means you can change the fields of objects but you can't add or remove items from the data structure. Nor are you allowed set a whole new object to one that is already in the list. If you modify the list, there will be a ConcurrentModificationException thrown.
Are you asking about this:
for (Animal a: animals)
{
a=new Dog(); // wrong
}
If so, think of a as defined in this case as final Animal a. Therefore the reference variable is immutable. But the member fields of the objects (if any) are not necessarily immutable.
for (Animal a: animals)
{
a.Name = "Jack"; //valid, if Name is a mutable member field.
}
I am trying to get more familiar with java recently. A question occurred to me which I couldn't find the answer online. I am wondering when java adds an element to an arraylist, is the added element associated with a variable name? For example in the following code:
E obj1 = new E();
E obj2 = new E();
List myList = new ArrayList<E>();
myList.add(obj1);
obj1 = obj2;
After the new assignment to obj1 will the value exist in myList change or not?
No, when adding an object to a List, the reference is copied and therefore when you assign obj1 with new value, the list will contain the old one.
In Java, it's "all about references".
A new instance is created only when you use new.
In all other assignments, such as obj1 = obj2, you are only changing the reference to the actual instance.
The only exception for this rule are assignments that involve primitive types such as char and int.
When you do myList.add(obj1), you add an entry in myList, which contains a reference to the instance referenced by obj1.
At this point, this instance has two references (one by obj1, and one by the entry in myList).
When yo do obj1 = obj2, the same instance remains with only one reference (in myList).
When the number of references to an instance becomes 0, it is deleted by the garbage collector.
No ,in your case obj1 will not change in ArrayList because you already added obj1 to ArrayList before changing the obj1 to obj2.
ArrayList is as same as Array excepts its dynamic expending features.
ArrayList is container, internally it is having a array inside it, which stores object reference.
myList.add(obj1);
This will store the reference value not reference to list.
obj1 = obj2;
This will does not effect any change in list.
After obj1 = obj2;, first instance of object E is destroyed because both of obj1 and obj2 are pointing to the same instance (the one from line 2 E obj2 = new E();).
Java is always pass-by-value. That means that the original variable before you pass it is never changed by anything done inside methods/objects/etc that you call.
However the thing that confuses people here is that when you pass an object you actually pass a reference to that object by value.
Which is what is giving you the behavior here.
You have passed a reference to the object into the list. The reference has been passed by value. That means it has been copied, and you can change the reference (but not the thing it points to) as much as you like and the method you called will not see any change.
Before this question is answered the first thing to remember is that whenever you come across object is assigned to another object , you need to consider that reference is like remote control to the object. but in case object is assigned to another object , your reference(remote control) no longer controls your obj.
lets go line by line to see whats happening:
E obj1 = new E();
// the obj1 is created and holds reference to a memory location let's say 1a2s3d
E obj2 = new E();
// the obj2 is created and holds reference to say 5g5g5g5 .
List myList = new ArrayList<E>();
// empty list created acception elements of type E
myList.add(obj1);
//myList now points to reference 1a2s3d by addition of obj1 .
obj1 = obj2
//obj1 and obj2 now point to same reference .. 5g5g5g5
and myList still points to reference 1a2s3d because it points to reference not obj1.
So its value will not change.
Also any new changes to elements of obj1 or obj2 like setting value of any field in obj1 of class
E will change value of that field in obj2 also . thus the code is (obj1==obj2) ?? will return true.
obj1 contains a reference to an instance of the class E. When you 'add' the object to the list you are adding the reference to it so the list knows who is the new buddie.
When making obj1 = obj2 you are changing the value of obj1, not the instance itself, so that both variables point to the same instance of E.
Object variables are just a reference, so you are just changing the reference. Therefore, the instance you created with
E obj1 = new E();
is still alive and not changed at all.
By making an assignment of object variables you will never ever change the object itself but the reference.
Note: if an instance remains without being pointed by some variable the garbage collector of java will delete it. This is not the case as the instance is now pointed by the list.
Suppose my code goes like this:
ArrayList list = new ArrayList();
Student s = new Student(); // creating object of Student class
myList.add(s); // Here am confused ...
/* myList contains just the reference variable to the Student object, OR
myList contains the actual Student object (memory allocation for name, rollNo etc) ??
*/
In Short when adding objects to ArrayList using add():
ArrayList is a list of "References to objects" or its a list of "actual objects" ???
In Java, you never pass around actual objects. You are always dealing with a reference, which is essentially just an address to a location within memory where your object is stored.
Since you never work with actual objects, ArrayLists contains arrays of references to objects stored somewhere else (a place in memory called the heap).
The objects are stored on the heap, not 'inside' the arraylist. The arraylist stores references to where there objects are found, as you say.
ArrayList stores references to objects. I would advise you to use the generic version of ArrayList.
Your declaration would be:
ArrayList <Student> list = new ArrayList<>();
You would benefit from type checking at compile time.
Also read http://en.m.wikipedia.org/wiki/Object_copy for explanations about object copy concepts and the different strategies adopted by Java and C++.
Objects within the ArrayList themselves are stored on the heap. The ArrayList simply provides references to those objects and the ArrayList instance is also on the heap.
Object references, at the end of the day, are simply addresses to locations within memory where the object is stored. Hence, the ArrayList contains arrays of references to objects stored on the heap (or in memory).
ArrayList stores the references of objects.
The snippet will explain to you
public static void main(String[] args) {
ArrayList<Dog> a=new ArrayList<TEST.Dog>();
Dog d=new Dog("AL");
a.add(d);
d.setName("AFTER");
System.out.println(a);
}
Here we are changing the Dog object independently out side of the list and it is getting reflected to the List, hence a reference is being stored in the list.
I know this is more specific than necessary, but Java stores an Object's reference by value. I would explain it, but there is already a good article here: Java is Pass-by-Value, Dammit!.
Scott Stanchfield also added some extra clarification on stackoverflow/reference-or-value.
Depends on how you see it.
But its always a reference.
Here is an example:
String niceText = "Hallo array List";
ArrayList<String> list = new ArrayList<String>();
list.add(niceText);
System.out.print(niceText + " = " + list.get(0));
// Output: Hallo array List = Hallo array List
niceText = "Goodby list";
System.out.print(niceText + " = " + list.get(0));
// Output: Goodby list = Goodby list
list.get(0) = "Still in here";
System.out.print(niceText + " = " + list.get(0));
// Output: Still in here = Still in here
list.add("New value");
System.out.print(niceText + " = " + list.get(1));
// Output: Still in here = New value
// But there is no referencing object anymore for index 1, it exist only in the list
But you can go much further, by cloning your object or pass it in different ways to other components of your app.
But this has nothing to do with the array list, this is how java handels object instances and there visibility.
ArrayList<Dog> arrayList = new ArrayList<Dog>();
Dog dogReference = new Dog("AL");
arrayList.add(dogReference);
System.out.println(arrayList.get(0)); //Dog#ObjectRef
dogReference.setName("AFTER");
dogReference = new Dog("NEWER");
// This is still referencing old reference though we have re-initialized
System.out.println(arrayList.get(0)); //Dog#ObjectRef
System.out.println(arrayList.get(0).getName()); //AFTER
System.out.println(dogReference.getName()); //NEWER
Initially, I was confused after this example as after re-initializing same variable arrayList still point to the older one. ArrayList uses Object[] to store the references.
I'll bite. This is obviously a question resulting from a larger issue about object references in Java. Perhaps it'll help to ask why you would need to know if your object is being stored by reference or by value.
That's probably the more interesting question to answer as most everything in Java, except primitives and a few others, are stored by reference. To be at a point where you're needing to think about why your thought process needs to know if something is by reference or value is more likely the point where you'll be able to resolve any issues that prompted you to have to ask this question.
Just curious.