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.
Related
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 have an ArrayList of objects.
I "retrieve" one of those objects with something like:
MyObjectClass myObject = myArrayList.get(34);
If I subsequently make modifications to myObject, such as:
myObject.someMember = 97;
is it just doing it to a local COPY of the object or the actual object within the array list? That is, is the myObject variable a copy or is it a REFERENCE to the object within the array list?
In Java, a name referring to an object always has reference semantics. Container get functions idiomatically return the same reference that the container holds.
If a function wants to return a local copy, or you want a local copy, this is done using new.
MyObjectClass myObject = new MyObjectClass( myArrayList.get(34) );
is it just doing it to a local COPY of the object or the actual object
within the array list? That is, is the myObject variable a copy or
is it a REFERENCE to the object within the array list?
Yes it will make changes in the object state which is in ArrayList
Neither. Both myObject, and the item in the arraylist, are references to the object which is stored elsewhere.
The ArrayList does not hold the object, only a reference to the object (just like your reference to the object). Objects are never stored inside other objects in Java, although sometimes it is convenient to think of them that way.
Basically i want to add students to a class list. Assuming i have the following code
public class ClassList {
//Constructor methods...
private Student [] studList = new Student [20];
public boolean addStudent (Student newStudent)
{
studList[14] = newStudent;
}
}
Does studList[14] add a reference to newStudent object or copies that object into the studList[14] student object?
As far as i understand newStudent object will get deleted when the method addStudent() is called a second time. So studList[14] will point to null then? What if i want studList[14] to persist throughout the code execution?
Sorry if it is hard to understand, i do not know how to explain my query easier...
There's one fundamental rule in Java that you have to wrap your head around:
The only way you can access an object is via its reference. And the only values that variables can hold are references(*). That's true for local variables, parameters, instance fields and static fields: they all are the same in this respect.
The object itself is never "contained" in a variable.
This directly leads to the answer to your first question:
The reference is copied into the array (as an array can only hold references(*), never objects).
This also mean that "newStudent being deleted" is not actually a big deal: it's just another reference to the same object, and if it goes away nothing much happens.
Now, if all references to a given object are removed (or no longer reachable), then the object itself becomes eligible for garbage collection, but that's not a bad thing, because you could not access it anymore anyway.
(*) ... or primitive values, but we'll ignore those for this dicussion.
The assignment doesn't copy the object. It just adds a reference to the object into the array.
An object gets deleted by the garbage collector after there are no more references to it anywhere. You don't need to worry too much about this process, because it's kind of invisible most of the time; and once there are no references to an object, you couldn't have used it anyway.
Perhaps you want to be able to pass in an int to your method, to tell it which entry in the array to set, instead of always setting entry number 14?
You should have a look at the JLS about types, values and variables:
The values of a reference type are references to objects.
If there is no remaining reference (aside weak ones) to an object it will be garbage-collected out of the heap.
If you call two times: addStudent(new Student());
the first Student object created is qualified for GC since you have no other reference variable "pointing" to the object.
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.