Modifying object collections - java

I'm working in some Java code and I have a doubt. I have a loop that goes along a Collection to modify each one of its objects with a method. The thing is, when you pass an object to a method, what are you really passing? A copy of the reference? the memory address? Here is my code:
for(Iterator it = colDesglosesBDI.iterator(); it.hasNext();)
{
DesgloseBDIVO desgloseBDI = (DesgloseBDIVO)it.next();
desgloseBDI = completeDesgloseAgrup(desgloseBDI);
}
The method completeDesgloseAgrup returns a DesgloseBDIVO Object so I can replace the old objects with the new attributes. But maybe I can do it by this way:
for(Iterator it = colDesglosesBDI.iterator(); it.hasNext();)
{
DesgloseBDIVO desgloseBDI = (DesgloseBDIVO)it.next();
completeDesgloseAgrup(desgloseBDI);
}
And in this case the method would be void and do not return any object. Is possible to do it in that way?
Regards

Yes that is entirely possible provided the completeDesgloseAgrup() method only changes the attributes of the argument, and does not try to replace it with a new object.
Consider this:
public void completeDesgloseAgrup( DesgloseBDIVO d )
{
// will work, callee will see "something"
d.setSomething( "something" );
}
public void completeDesgloseAgrup( DesgloseBDIVO d )
{
// Won't work, as Java has call by value semantics. Callee won't see the new DesgloseBDIVO in callee's scope.
d = new DesgloseBDIVO()
d.setSomething( "something" );
}
Cheers,

In java objects are data structures on the heap which you reference by variables, hence you never pass the objects, always the reference to an object.

From "The Java Programming Language, 4th edition" by Ken Arnold, James Gosling and David Holmes:
The Java programming language does not pass objects by reference; it passes object references by value. Because two copies of the same reference refer to the same actual object, changes made through one reference variable are visible through the other. There is exactly one parameter passing mode pass by
value and that helps keep things simple.

Related

Question about the Java documentation and its implementation

I'm currently sitting at an exercise, which wants me to create a Java program based on an already finished documentation HTML sheet.
For example, one entry states
reversedArray
public static Object[] reversedArray(Object[] array)
Based on the name, we can assume the method should return an array in the reversed order of array.
Now my question isn't about how to create the said array, but more about the Object[] terminology. What does it mean? Should I create a bunch of methods through overloading each with a specific array type (e.g. String[], int[], ...) or literally an Object[]?
It's the latter, how does an object array work? Based on the name, I assume it's an array that can hold objects, but I'm unsure what this means in practice.
Object[] is basically just an array of objects (best explanation award right here please ----> ☐ )
Jokes aside, in Java, any object is derived from the class Object so basically, this array can store any object of any class. It's mostly useful when you just want to carry an instance (or several instances) of different classes, but the type of said instance is not important.
Let's say you have multiple classes that are not necessarily related :
Class Dog {
String name;
public Dog(String name) {
this.name = name
}
public String toString() {
return "Hello! I am a dog called " + this.name;
}
}
Class Refrigerator {
public Refrigerator() {
}
public String toString() {
return "I am a refrigerator";
}
}
Since both classes are implicitly derived from Object and that Object implements the method toString() you can override that method in both of you class declarations.
Then you can store any instance of these in a Object and call the method toString(), like so :
Dog myDog = new Dog("Spike");
Object anyObject = myDog;
System.out.println(anyObject.toString()); //would print the result of your "toString()" method in the Dog class :
//"Hello! I am a dog called Spike"
Refrigerator myFridge = new Refrigerator();
Object secondObject = myFridge;
System.out.println(secondObject.toString()); //would print the result of your "toString()" method in the Refrigerator class :
//"I am a refrigerator"
This allows you to create a method that accepts any object and treats them the same and assign any object in argument :
public void printWhatYouAre(Object o) {
System.out.println(o.toString());
}
public void doingSomething() {
Dog myDog = new Dog("Spike");
Refrigerator myFridge = new Refrigerator();
printWhatYouAre(myDog);
printWhatYouAre(myFridge); //would print the same as above
}
In your case, your method only needs to rearrange an array, which means it doesn't even need the method toString nor does it need to know what the objects are. It just needs to store an array of something into an other array of something in a different order.
Here is a nice reading about polymorphism in Java, which is basically applicable in any language, but the examples that are used are wrote in Java. The whole site actually is a pretty good reference, so it's worth taking a look, especially the OOP sections which are the most related to your post. ;)
As the name already states, the method should create a new array in
the reversed order of "array".
The method name only says to "reverse" the array; whether it's just a matter of modifying the actually supplied array or constructing a new one is something you'll need to clarify with the author of the requirement if it's not clear.
Now my question isn't about how to create said array, but more about
the "Object[]" terminology. Basically, I'm unsure what to do. Does
said "Object[]" mean, I should create a bunch of methods through
overloading each with a specific array type (e.g. String[], int[],...)
or literally an Object[] array?
No, you only have to create overloads for the primitive types i.e. int[], long[] etc and that's only if your requirement says so. the aforementioned method should be able to consume Object[], String[] , Integer[] , Double[] etc...
It it's the latter, how does an object array work? Based on the name I
assume, it's an array that can hold objects, but I'm unsure what this
means in practice.
The method name has nothing to do with what an array can hold, the method argument is an array of Object's and it's as simple as that.
Reading you might find useful:
Arrays

Questions with updating objects in java

If I have an instance of an object, and within that object is a variable that holds the data of another object. If I ever update the second object will the copy of that object be updated as well or do I need to simultaneously update all copies of said object.
For example:
public class Object()
{
int x = xValue;
Object linked = saidObject;
}
public class doStuff()
{
saidObject.x++;
if(linked.equals(saidObject))
return true;
}
will this code (not compilable obviously just fill in blanks) return true?
if(linked.equals(saidObject)) will return true as the two variables do point to the same object.
In Java all variables and fields are references to an actual Object that lives somewhere in memory.
When you assign one variable to another, it's like copying the address of the object so that they both point to the same object in memory.
e.g.
Object a = new Object(); // this actually creates the Object in memory
Object b = a; // this copies the reference to Object from a to b
// At this point, a and b point to exactly the same object in memory. Therefore ...
a.equals(b); // returns true.
In fact a == b returns true too, which is a better way of comparing for this case as == compares if two variables point to the same object (they do), whereas equals() often compares by value, which is unnecessary here.
It doesn't matter if b is actually a field within a (e.g. class Obj { Obj b; }; Obj a = new Obj(); a.b = a;) and it points to the same type of object, the principle is the same: a = b means they point to same object, nothing new is created.
By doing:
Object linked = saidObject;
you are not copying the object, just creating another pointer to it, it means you have two different pointers that point to the same object.
copying or cloning an object can be useful in some cases but its not the usual case.
An object instance is itself and is distinct from every other instance.
That is, mutating an object (by reassigning a field) someplace modifies it everywhere .. as, well, it is what it is. Likewise, mutating a different object .. is, well, changing a different object.

Java Pass-by-Value Confusion

Ok bit of an odd question. I have the following code, which just creates a simple java object called DumObj and sets a string value using a setter method. Then a few methods are called from a TestBed class using the DumObj as a parameter.
I initially thought that calling TestBed.updateId(DumObj) would not affect my DumObj, and the initial value of ID that was set to "apple" would stay the same. (Because of the whole pass-by-value thing)
However the value of ID was set to the updated value of "orange". Ok I thought, that's weird, so I wrote another method, TestBed.setToNull(DumObj). This method just sets DumObj to null, so when I call the getId() method I was expecting to get a null pointer exception.
However the output I got was the value of ID still set to "orange".
Code is as follows :
public static void main(String[] args)
{
TestBed test = new TestBed();
DumObj one = new DumObj();
one.setId("apple");
System.out.println("Id : " + one.getId());
test.updateId(one);
System.out.println("Id : " + one.getId());
test.setToNull(one);
System.out.println("Id : " + one.getId());
}
public void updateId(DumObj two)
{
two.setId("orange");
}
public void setToNull(DumObj two)
{
two = null;
}
Output is as follows :
Id : apple
Id : orange
Id : orange
It's probably something really simple I'm overlooking, but can someone explain this behaviour to me? Is Java not pass-by-value?
When you write
DumObj one = new DumObj();
it's important to realise that one is not a DumObj - it's a reference to DumObj, and references are passed by value.
So you're always passing by value, and you can change the passed reference (so your passed reference now points to a different object). However, your object itself could be mutable, so this:
one.setValue(123);
will change the referenced object. When you call this:
public void setToNull(DumObj two)
{
two = null;
}
you're changing the passed reference (remember - it's been passed by value and is local to the method!) and so your original object and original reference are not affected.
When you do:
two = null;
You are only setting the two variable reference to null. The object that it was pointing to still exists, and is referenced by one.
On the other hand, when you do:
two.setId("orange");
You are modifying the object that is referenced by both one and two.
Java is kind-of "pass reference by value" for objects. So in setToNull(DumObj two), two is a reference to an object. If you say two = null;, that now makes two a reference to not an object; it doesn't change the object. If, on the other hand, you do something like two.setId("blue"), you are changing the object that two references.
When you call updateId the new reference variable two and old reference variable one both referring to same object in heap so changing one gets reflected in other reference variable.
now when you call setToNull again new reference variable two and old reference variable one both referring to same object.But here when you do two = null only reference variable two point to null object. but reference variable one still pointing to same object.When you do two==null ,you are not changing any value in object referred by it but instead you are referring reference variable to null.
In case in setToNull method you write two=new DumObj(); then a new object in heap will be created and two will point to this new object .and then for ex if you write
two.setId("banana");
and in your main code if you write one.getId() inside syso then it will print orange not banana.
hope i helped.
Yes, Java is pass by value. But your variables are really pointers to the object allocated on the heap. So what its passed by value is the pointer, not the object.
In your examples:
public void updateId(DumObj two)
{
two.setId("orange");
}
The first passes the variable (pointer) by value, that is, updateId() recieves a copy of the pointer. But what you are doing here is to modify the object pointed by the pointer. So the object was modified when you return to the caller function.
public void setToNull(DumObj two)
{
two = null;
}
In the second case, you are assigning null to a copy of the original pointer, not the original pointer itself, so that function call has no effect at all in the origial variable.

Pass by value or Pass by reference in Java?

I read many articles and all says Java is pass by value. But i still don't construe the difference between pass by value and reference. I wrote a sample program and it executes like this..
public class PassByValue {
private int a;
private int b;
public PassByValue(int a, int b) {
this.a = a;
this.b = b;
}
public static int mul(int a, int b) {
int z = a * b;
System.out.println("The Value of Z inside mul: " + z);
return z;
}
public static void main(String args[]) {
int z = 100;
int x = 40;
int y = 20;
mul(x,y);
PassByValue pass = new PassByValue(x,y);
mul(pass.a,pass.b);
System.out.println("The Value of Z" + z);
}
}
Execution
800
800 and
100
Can anyone explain me these questions...
What is Pass By Value means...
Answer: Its just passing the numbers or value stored in the variable to a function. Am i right or wrong.
How do you say Java is Pass By Value?
Why is Java is Pass By Value and not by reference?
Does the above program Tries shows an example of Pass by value and Reference... but still does things via Pass by Value only... I wrote that program.
The confusion is probably due to the fact that a variable can't contain an object in the first place. A variable can only contain a reference to an object. (In other words, objects aren't passed at all, not by reference, not by value.)
Once you realize this, it is quite clear that nothing is pass-by-reference in Java. A variable refering to an object stores a reference, and this reference is passed by value.
1. What is Pass By Value means...
Answer: Its just passing the numbers or value stored in the variable to a function. Am i right or wrong.
That's right. The value contained in the variable is passed, and not the variable itself.
1. How do you say Java is Pass By Value?
Java is pass by value because primitives are passed by value, and references are passed by value. (Objects are never passed.)
You can't implement a swap method in Java for instance. I.e., you can't do
String str1 = "hello";
String str2 = "world";
swap(str1, str2);
// str1 can't refer to anything but "hello"
// str2 can't refer to anything but "world"
2. Why is Java is Pass By Value and not by reference?
As explained above, even references are passed by value.
You are right in your answer, but you are lacking detail. If you do
Dog d = new Dog()
d is a reference to an instance of Dog, i.e. What pass by value means is that you when pass d into a method
walkDog(d);
the a copy of the reference (i.e. the value of the reference, not the reference itself) to the Dog is passed into the method. So you have 2 references to the one instance of the Dog, the one in the calling scope, and the one in the called scope. Lets say in the walkDog method there is a line
d = new Dog();
the d reference in the method only points to the new Dog. The original reference where the method was first called still points to the original Dog. If Java had pass by reference, the same reference, not a copy of the reference would be used in the method, and so changing the value of the reference would affect the reference in both the calling and the called scope.
EDIT -- based on your comment, I want to make on thing clear. Since the reference in the original scope and the method scope both point to the same object, you can still change things on that object in both scopes. So if you do
d.drinkWater();
in the walkDog method, and drinkWater changes some variable on the dog object, then since both references point to the same object, which was changed.
It's only a distinction between what the references actually are in each scope. But it does come up a lot.
You can think of pass-by-value as passing only the value contained in the variable and not the variable itself. So then the value is copied into another temporary variable. In contrast, you can think of pass-by-reference as passing the actual variable and no temporary copies are made, so that any changes in the variable is 'saved'. Although there is more to it, it might be easier way to thinking about it
I think instead creeping around if Java supports pass by reference or values, one should be clear about the way of using the instances of the classes in Java in his implementation. It all happens to be the type of instances - mutable/immutable which is gonna decide the way we pass things to the functions! That's up to you to explore this difference!
Let me clarify my argument of why there is no need of chasing back at passing what?! Consider this...
First Code:
void foobar(int *a){
printf("%d", *a);
}
int main(){
int a = 5;
foobar(&a);
return 0;
}
Here in this C code, what are you passing... the address of the variable 'a'. This happens to be the pass by reference! :)
Let us consider another one...
Second Code:
void foobar(int* a){
printf("%d", *a);
}
int main(){
int a = 5;
int *p = &a;
foobar(p);
return 0;
}
Here in this C code, what am I passing....? The value of the variable 'p', doesn't matter whether it is pointer or something :P
So what do you call this as pass by value/pass by reference? I leave this to you! But all we need to look at is how we gonna implement... :)
So in Java... with what we pass we can say - It supports "Pass by value" or "Pass by reference of some instance" and not "Pass by reference"
***Only thing which I can clearly conclude is with the primitive data types in Java. Since there is no pointers with which one can edit the content of a byte without the actual variable, we can't have pass by reference for them(I mean the primitive data types) in Java.

Objects and primitives in methods

Please advice why primitives being used as method's parameters do a copy of its value while objects are used as is?
In Java, all arguments are passed by value - but in the case of reference types (i.e. everything other than a primitive) the value of a variable isn't the object itself - it's a reference to the object. Thus that reference is copied into the method's parameter, so it refers to the same object.
Note that this doesn't just apply to method calls:
StringBuilder x = new StringBuilder();
StringBuilder y = x; // Copy the value of x, which is a *reference*
y.append("Hello");
System.out.println(x); // Prints "Hello"
Here, x and y refer to the same object, even though they're separate variables. Thus when the contents of that object is changed via the append call through the y variable, the change is visible via the x variable too.
I think of it as being a bit like giving someone the address of your house: if I give two people my home address, and one of them paints the door red, then when the second person visits the house, they'll see the red door too. I'm not giving them my house itself, I'm giving them a way of getting to my house.
There are many, many articles about this - although unfortunately some will claim that objects are passed by reference in Java. They're not - the references are passed by value, as I said above. Scott Stanchfield has a good article about this, amongst many others.
To expand on what Jon Skeet said, primitive types are usually quite small - a double is 8 bytes. Objects, on the other hand, can be HUGE, and so passing a reference to them saves time and stack space versus copying the whole thing. Plus this allows you to modify the contents of the Object.
That's what it looks like but is not. Java is always pass by value.
When you declare something like this:
Date aDate = new Date();
The variable aDate is not really an object, but an object reference. When you pass that object reference to another method, a "copy" of that reference is passed ( just like with primitives a copy of the value is passed )
Now, since those two copies "reference" the same underlaying object, you see that sending a message on one of them affects the other, but if you change the reference to assign a new one, the other doesn't change.
For instance:
class Some {
int data = 0;
}
class Other {
void doSomething( Some o ) {
o.data = 10;
}
void change( Some a ) {
a = new Some();
a.data = 1024;
}
}
class Main {
public static void main( String [] args ) {
// create an object and get its object reference
Some original = new Some();
System.out.println( original.data ); // prints 0
// now pass it to a method from the class "Other"
Other o = new Other();
other.doSomething( original );
System.out.println( original.data ); // prints 10, because data was changed in "doSomething"
// To probe that the reference is not passed, but a copy of it
// invoke the "change" method.
other.change( original );
System.out.println( original.data ); // remains 10, instead of 1024.
// the value 1024 was changed in the new reference, and the one passed along
// didn't change. It still refers to the original object.
}
}
I hope this helps

Categories