ArrayList and Singleton object in Java - java

I am facing a small problem with Java ArrayList and singleton Object.
I collected some data and put them to this singleton Object and put it into the ArrayList. I need to know, will it refer to the original Object or get a copy of that Singleton Object. I need to get separate copies to put in ArrayList.
Explain in detail...

An ArrayList contains references to objects. Whatever references you put in the ArrayList, those references will be stored in there. For example, if you put 10 references (say r1, r2, ..., r10) which point to the same object, then you'll have an ArrayList of size 10 but all its members will point to the same object. This is how this works. So don't get confused, the ArrayList knows nothing about whether your objects are singletons or not, it deals just with storing references to objects.

The list will store an original reference to your singleton.
I don'get it why you are going to get copies of singleton. This is not how a singleton works.

Related

Object reference clarifcation

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.

Storing objects in array of objects

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.

Best way to transfer value from an ArrayList to another

With 2 ArrayList, I was wondering if the best way from transforming the 1st one into a "copy" of the second one is to go like
myFirstArray.clear();
myFirstArray.addAll(mySecondArray);
or
myFirstArray = mySecondArray.clone();
What are the main differences between those two method, which on is preferrable and is there another "easier" or "cleaner" solution. Thanks for any tips
EDIT : I use this copy for replacing an Array of item im currently working with the one where I store the item I'll work with in the next loop. At the end of the loop I replace my currentArrayList with my futurArrayList and I clear my futurArraylist in order to add new item in it (i hope its clear enough)
The first one replaces the content of the list by another content. The second one creates another ArrayList instance, leaving the previous one untouched.
If the list is referenced by some other object, and you want this other object to be untouched, use the second one. If you want the other object to also have the new content, use the first one.
If nothing else referenced the list, it doesn't matter much. The second one will reduce the memory used in case you replace the content of a huge list by a few elements.
In java, though clone is ‘intended’ to produce a copy of the same object it is not guaranteed.
Clone comes with lots of its and buts. So my first advice is to not depend on clones.
By default, java cloning is ‘field by field copy’ i.e. as the Object class does not have idea about the structure of class on which clone() method will be invoked. So, JVM when called for cloning, do following things:
If the class has only primitive data type members then a completely
new copy of the object will be created and the reference to the new
object copy will be returned.
If the class contains members of any class type then only the object
references to those members are copied and hence the member
references in both the original object as well as the cloned object
refer to the same object because of that cloned object changes are visible in original also.
Use that:
List<Object> first = ...
ArrayList<Object> second = new ArrayList<>(first);
I also suggest that you do not use clone() at all. It's better to use a copy constructor or some factory method. Take a look at here.
Of course in your case, with the ArrayList, it will work as expected, you will end up with a copy of the references.
Guava, guava, guava!
final List copied = ImmutableList.copyOf(originalList);

What's the 'canonical table'?

`What's the 'canonical table?I can't find any description of it.Can anyone provide a example?'
Are you reading Java Performance Tuning? I saw those concepts in there.
A canonical object means an object with a single reference pointed to it, with no copies holding the same state possible.
The activity of replacing multiple copies of an object with just a few objects is often referred to as canonicalizing objects.
For example Boolean, could have been canocalized, but it were not because new objects can be created with new, thus it's possible to create more than one instance with the same state.
A Canonical Lookup Table is some sort of cache containing references to those canonical object pool.

What's the most elegant workaround for inability to pass by reference in Java?

I have deep nested structures, and methods like "remove(<Something>)", "contains(<Something>)" etc. rely on access to the original reference in order to remove it etc. (a copy of the reference won't do).
How have people best worked around this so they can still conveniently add, remove, test for etc. the object they want, within different arbitrary methods and constructors etc., without adding any unnecessary complexity or any unnecessary loss in performance?
Methods like remove and contains work fine with pass by value. The reason is that the even though the references are copied, they copy has the same value of the original. Just look at the Collections API. If you do something like (psuedocode)
List list = new List();
list.add(object1) // assume you have an object1 reference
and then you do
myRemove(list, object1);
both list and object 1 are passed by value, so in the myRemove method they are copies of the original reference. If in myRemove you do
list.remove(object1);
the object is still removed from the list no problem. Furthermore, since the list and object1 references in both scopes point to the same underlying objects, the list reference in the calling scope refers to the list that has the object removed.
The only time you would need pass by reference semantics is if you want to modify a reference in a method and have the modification apply in the scope that called the method.
So if you want to do
List myList = new List();
changeList(myList);
and have changeList change where myList points in the calling scope, it wont work without some trickery. The trickery is called double indirection. Basically, you create an object that has an instance of what you want to be able to access with pass by reference semantics, and you pass the container object around.
So
class MyContainer {
List list
}
now you can pass an instance of MyContainer into a method, and change the list value, and in the calling scope where the list points will be changed. Note that you are not doing anything special here, everything is still pass by value.
How have people best worked around this so...
By use of member fields (for working with references, not copies) and by use of inheritance and interfaces (for handling nested structures).

Categories

Resources