Comparison of an old variable to a new one after some calculations - java

variable1 = value_of_A;
for loop {
//some calculations over value_of_A,
//so it is not anymore the same as in variable1
}
variable2 = value_of_A;
When I compare variable1 and variable2 they are the same ALL THE TIME. I have tried new class so a setter can store the value, methods, all type of variable definitions etc.
Possible solution so far: to write variable1 to a file, and then read it after the for loop. This should work, but any other solution?

I guess your problem is that you are working with objects, and in Java objects are passed by reference. It means, that you may have one object and two variables referencing it, and when you change the object via the first reference variable (variable1), the second reference variable (variable2) now gives you access to the same object, that has changed. Your solution is to create a new object inside your loop and assign a reference to this new object to your variable2, so that you will have to distinct objects with a single reference to each one of them.
// suppose this is the class you are working with
public class SomeObject {
private String nya;
public SomeObject(String value) {
nya = value;
}
public String getValue() {
return nya;
}
public void changeByValue(int value) {
nya += "Adding value: " + value;
}
}
// and here comes the code that changes the object
// we assign the first variable the original object
SomeObject variable1 = someObject;
// but we do not assign the same object to the second one,
// instead we create the identical, but new object
SomeObject variable2 = new SomeObject(someObject.getValue());
for (int i = 0; i < 10; i++) {
// here we change the second (new) object, so the original stays the same
variable2.changeValueBy(i);
}
System.out.println(variable1 == variable2); // false
System.out.println(variable1.equals(variable2)); // depends on implementation

In Java, when working with objects, you're actually just having a reference to that object. That means, if you have something like this
SomeObject o1 = new SomeObject();
SomeObject o2 = o1;
then o1 and o2 point to the same object, thus changes made in o1 are also affecting o2. This is called Aliasing.
In order to compare two different objects you could for example use a copy of your object before changing it in your for loop.
// This is the object we want to work on.
SomeObject changing = new SomeObject();
// Copy-Constructor, where you assign the fields of 'changing' to a new object.
// This new object will have the same values as 'changing', but is actually a new reference.
SomeObject o1 = new SomeObject(changing);
for loop {
// This operation alters 'changing'.
someOperationOn(changing);
}
// Again, a copy constructor, if you want to have another, different reference.
SomeObject o2 = new SomeObject(changing);
Now you have two objects o1 and o2 which doesn't affect each other anymore.

What is the type of your variables? It seems to me that it is a "by value" vs "by reference" issue. Look at this question here.
Essentially, depending on the type of your variable, the "=" followed by calculations does not create a new object. You just have one more reference to the same object in memory.

Related

How to get access to existing objects with string input (Convert string input to objectname)

I am creating a lot of objects called: Obj1, Obj2.... ObjX
Object Obj1 = new Object();
Object Obj2 = new Object();
Object ObjX = new Object();
Now I am having a function where I want to get access to one of this objects.
public void useObject(int objectNumber) {
String objectName = "Obj" + objectNumber;
objectName.doAnythingWithThisObject();
}
Is something like that possible in C# or Java? I don't want to use something like:
switch(objectNumber) {
case 1:
Obj1.doThis();
break;
case 2:
Obj2.doThis();
break;
If I would use switch/if-else then I have to repeat a lot of code which make this thing less readable, because I have to call the same function with different objects.
The actual answer is: you shouldn't, generally speaking, access your variables, using strings at runtime. Cases where this is actually appropriate are few and far between and your example, simplified though it may be for illustration purposes, is not a good match for it.
Instead, why don't you simply use a collection or an array to store your objects? #T.R.Rohith gives an example in their answer.
Still, the direct answer to your question, as it applies to Java, is given below. While the code would be different for C#, the language feature, which can be used for this purpose, namely, reflection, is available in C# as well.
If Obj1, Obj2 etc. are declared as static or instance fields in a class, you can get their values by their names using reflection (see relevant docs for Java). If they are local to a method, there is no simple way to do so (see these questions: for Java, for C#).
Static fields
class Something {
static Object obj1 = new Object();
static Object obj2 = new Object();
// etc.
}
(I've taken the liberty of starting field names with lowercase letters, as it the accepted practice in Java.)
In this case you can get the value of the variable by its name using the following code (you need to import java.lang.reflect.Field):
// Get field, named obj1, from class Something.
Field f = Something.class.getDeclaredField("obj1");
// This line allows you access the value of an inaccessible (non-public) field.
f.setAccessible(true);
// Assigning the value of the field, named obj1, to obj.
// You may want to cast to a more concrete type, if you know exactly what is stored in obj1.
// The parameter for get() is ignored for static fields, so simply pass null.
Object obj = f.get(null);
// Now you can do whatever you want with obj,
// which refers to the same object as static field obj1 of Something.
System.out.println(obj);
Instance fields
class Something {
Object obj1 = new Object();
Object obj2 = new Object();
// etc.
}
You can do it in almost exactly the same way for instance fields, you just need an instance of the class to pass to f.get(). So, for the sake of example, let's assume we have an instance of class Something, called sth.
// Let's say this is an instance of our class
Something sth = new Something();
// ...
// Get field, named obj1, from class Something.
Field f = Something.class.getDeclaredField("obj1");
// This line allows you access the value of an inaccessible (non-public) field.
f.setAccessible(true);
// Assigning the value of the field, named obj1, to obj.
// You may want to cast to a more concrete type, if you know exactly what is stored in obj1.
// The parameter for get() is the instance of Something,
// for which you want to retrieve the value of an instance field, named obj1.
Object obj = f.get(sth);
// Now you can do whatever you want with obj,
// which refers to the same object as instance field obj1 of sth.
System.out.println(obj);
Local variables
You are probably out of luck in this case. Again, see the following links: Java, C#.
This sounds like a classic Strategy pattern problem Strategy Design Pattern
Here's the code:
//Declare this in the class so that it can be called by any method
static Object[] array = new Object[4];
public static void main()
{
//Use this to initialize it
Object[] array = new Object[4];
for(int i=0;i<4;i++)
{
array[i] = new Object();
}
//You can now easily call it
useObject(0);
useObject(1);
useObject(2);
useObject(3);
}
//Your numbers may be off by 1 because we are using an array but that is easily adjusted
public static void useObject(int objectNumber)
{
array[objectNumber].doAnythingWithThisObject();
}
The answer is... don't. Use an array instead. This is exactly what they're for.
ObjectType[] objectArray = new ObjectType[10]; // Or as many as required.
for (int i = 0; i < objectArray.length; i++) {
objectArray[i] = new ObjectType(); // Or whatever constructor you need.
}
// Then access an individual object like this...
ObjectType obj = objectArray[4];
// Or...
objectArray[5].someMethod();

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.

Object Reference passing in Java. Pass by reference working differently in different case?

While playing in Java. I saw different behaviour if an object is modified and given a value and different value if it is assigned a new object. Here is code that I made to show the result.
public class Test {
int i;
public Test(int j) {
this.i = j;
}
public static void main(String[] args) {
Test A = new Test(5);
Test N = new Test(5);
add(A);
makeNew(N);
System.out.println("Value of A.i= "+A.i);
System.out.println("Value of N.i= "+N.i);
}
private static void add(Test t) {
t.i+= 3;
System.out.println("Inside method add() t.i= "+t.i);
}
private static void makeNew(Test t) {
t = new Test(8);
System.out.println("Inside method makeNew() t.i= "+t.i);
}
}
Here is the output of the above code.
Inside method add() t.i= 8
Inside method makeNew() t.i= 8
Value of A.i= 8
Value of N.i= 5
In above example object A is modified to value 8. And object B is given a new object itself. But calling them back only object A shows new value. Object B shows the old value itself. Should not they be showing same value because both case are pass by refernce? I was expecting same value for A.i and N.i.
Here's what happens:
Test A = new Test(5);
Test N = new Test(5);
add(A); // method is add(Test t)
makeNew(N)// method is makeNew(Test t)
t = new Test(8);
System.out.println("Value of A.i= "+A.i);
System.out.println("Value of N.i= "+N.i);
Whenever you make a variable equal to an object and later use new on that object somewhere else like through another reference, your variable you set to the objects reference no longer points to whatever the new object is, but still holds onto the old. So if multiple variables at different scopes hold a reference, they all need a way to have them made equal to whatever the new object is or they no longer are in synch.
I think this will make you doubt clear:
You see N still point to the first object
In your makeNew, you're overwriting the reference to the existing object (that's passed in as the paramter) with your new test(8) object. However, that's local inside makeNew, so the original object sitting inside main(...) is not affected.
Java is pass-by-value. You pass the reference of an object as a value, and you can thus modify that object. However, you cannot modify the actual reference of an object and make it point to something else.
Your question has already been answered here: Is Java "pass-by-reference" or "pass-by-value"?
In Java you do not pass the actual object nor do you pass the reference to the object. You pass copy of the reference to that object. Now when you say
makeNew(N);
N which is the reference to new Test(5) is not passed but the copy of it's reference is passed. In the makeNew() function this copy points to some new object and print the value appropriately but the N will still point to the original object.

How passing an Object as argument differs from passing an Array as argument?

I have come across two scenarios.
One in which an array is passed as argument to a method and if it is updated in the called method, it is reflecting in the calling method as well.
But in the second scenario, a String Object is passed as argument. The object is updated in the called method, but it doesn't reflect in the calling method.
I want to understand what is the difference between two, even though in both cases, value (of reference) is passed as argument. Please see below snippets.
Scenario 1:
class Test {
public static void main(String[] args){
int a[] = {3,4,5};
changeValue(a);
System.out.println("Value at Index 1 is "+a[1]);
}
public static void changeValue(int b[]){
b[1] = 9;
}
}
Output:
Value at Index 1 is 9
Here, reference (Memory Address) related to array a is passed to changeValue. Hence, b is just pointing to same address as a does.
Hence, whether I say b[1] or a[1], it is referring to same memory address.
Scenario 2:
public class Test {
public static void main(String[] args){
String value = "abc";
changeValue(value);
System.out.println(value);
}
public static void changeValue(String a){
a = "xyz";
}
}
Output:
abc
If I apply the same logic here, String Object VALUE's reference (Memory Address) is being passed to changeValue, which is recieved by a.
Hence, now a should be referring to the same memory location as VALUE does. Therefore, when a="xyz" is executed, it should replace "abc" with "xyz".
Can someone please point out where my understanding goes wrong? Thanks in advance!!
Java passes all its arguments by value. This means that a copy of the pointer to the String is made, and then passed to the method. The method then makes the pointer point at another object, but the original pointer still points to the same String.
This is not the same thing:
in the first example, you pass an array reference as an argument, therefore you correctly expect it to be changed by manipulating the reference directly;
in the second example however, you pass an object reference, sure -- but you change the reference itself in the method. Changes to a are not reflected when the method returns.
Consider any object:
public void changeObj(Object o)
{
o = new Whatever();
}
a new object is created, but it won't change o in the caller. The same happens here.
You're doing different things; with the string you set the parameter value, with the array you set something belonging to the reference.
For an equivalent array example you'd need to try setting the array reference to a new array:
public static void changeValue(int[] b) {
b = new int[] { 42, 60 };
}
The original array won't be changed.
The difference here is simple, and it is not actually about immutability of strings, as some other answers (now edited or deleted) might have originally implied. In one version (with the string), you have reassigned the reference, and in other version (with the array), you haven't.
array[0] = foo; // sets an element, no reassignment to variable
array = new int[] { 1,2,3 }; // assigns new array
obj = "hey"; // assigns new value
When you reassign the variable, you are not going to observe that change outside of the method. When you change elements of an array without reassigning the array variable, you will observe those changes. When you call a setter on an object without reassigning the actual variable of the object, you will observe those changes. When you overwrite the variable (new array, assigning new value, creating new object, etc.) those changes will go unobserved.
Arguments are passed (or copied) by value. The variable inside the method has the same value as the variable on the outside at the beginning. The variables are not linked, and they are not aliases for one another. They just happen to contain the same value. Once you reassign the value to one of them, that is no longer true! The variable on the outside is not affected by the variable on the inside, or even another local variable. Consider
Foo foo = new Foo();
Foo other = foo;
foo.setBar(1);
int bar = other.getBar(); // gets 1
foo = new Foo();
foo.setBar(42);
int bar2 = other.getBar(); // still gets 1
foo and other only referenced the same object for a time. Once foo was assigned a new object, the variables no longer had anything in common. The same is true for your reassignments to the parameter variable inside your method.
Thank you all for answers and updates..
I understood the difference between scenario 1 and 2 as below..
In scenario 1, the array reference is passed. The called method just updates one of the elements pointed by the reference.
While in scenario 2, the reference is passed, but when the called method assigns "xyz" to the reference variable (pointer), it actually creates a new String Object and its reference is assgined to a local reference variable 'a' (Pointer now points a different objct).
The code in called method is as good as
a = new String("xyz");
Hence, the object in called method and calling method are absolutely different and indepenedent and have no relation with each other.
The same could have happened with scenario 1, if instead of doing
b[1] = 9;
I would have used
b = new int[] {8,9,10};
I understood, Mutability fundamentals would have come in action, if I might have done like below..
String a="abc";
a="xyz";
In this case, object "abc" was being pointed by 'a'. When 'a' is assigned the duty to point to a new object "xyz", a new object "xyz" is created, which is not replacing the existing object "abc". i.e. "abc" is still existing but has no reference variable to keep itself accessible anymore. This non-replacement property is because of Immutability of String.

In Java, Is it possible to concatenate the value of a variable into a variable name (Sounds messed up, but please read details)

Basically I have a variable, zlort = one;
I want to concatenate the value of zlort into a variable (object reference) name.
Like
BankAccount Accountzlort = new BankAccount;
I want the zlort in Account.zlort to actually be the replaced with value of zlort (one--meaning I want the value to be Accountone), and not zlort itself.
Is it possible to do this?
Thanks!
No you can't, but you might put the instance in a map:
Map<String,BankAccount> map = new HashMap<String,BankAccount>();
map.put("Account" + zlort, new BankAccount());
If you mean dynamically choosing the name to assign a variable to, then no.
You could use a HashMap to achieve the same effect.
It is not possible to change the name of a variable at runtime. That would lead to extreme security and stability problems when dealing with any real-world application.
However, as the two answers here have mentioned, a HashMap might acheive what you are looking for. (See the javadoc!!)
A HashMap (or any other map, for that matter) maps a Key to a Value. The concept is similar to a variable, which is a name -> value mapping. The only difference is that variables are part of the actual program code, which is effectively unmodifiable after compiling. A Map is a data structure that can be modified by the running program. This allows you to freely add key-value pairings to it.
Note that in Java, type-safety is encouraged through the use of Generics. Basically this ensures that the key can only be of one type (e.g. String) and the value can be of only one type (BankAccount). A thorough coverage of Generics can be found here.
You would declare this as follows:
Map<String, BankAccount> accounts = new HashMap<String, BankAccount>();
And then to add a key-value pair to the map, you would use the put() method (which 'puts' a value into the map, associated with a key)
String key = "Key"
BankAccount value = new BankAccount();
accounts.put(key, value);
To retrieve it, you would use the get() method.
BankAccount retrievedValue;
retrievedValue = accounts.get(key);
After reading the explanations in your comments, the fact that you can't use an array but can use an `ArrayList'...
Rather than creating a new variable name (or array element, or map value) for each BankAccount, you can probably use scope to your advantage.
Scope is the concept that a reference to a variable only has meaning within a certain part of code. If you declare a variable inside a method, that variable can only be seen within that method. A variable declared within a block (a loop, if statement, etc ) can only be seen from within that block.
Class fields have a different kind of scoping that can be adjusted with keywords (see here).
For example:
public class ScopeExample
int classInt = 10;
public void method() {
int methodInt = 0; // This integer can only be seen by code in
// this method
}
public void method2() {
//doSomething(methodInt) // This line won't compile because i is
// declared in a different method!
doSomething(classInt); // This line will compile and work
// because x is declared in the class that
// contains this method.
int index = 0;
while (index < 3) {
int whileInt = index; // This integer can only be seen from within
// this while loop! It is created each
// loop iteration.
doSomething(whileInt);
}
doSomething(whileInt); //This line won't work, whileInt is out of scope!
}
public doSomething(int a) {
System.out.println(a);
}
}
SO! If you create a BankAccount object within the loop, you don't have to worry about creating a new name for the next one. Each time the loop iterates it will become a new object (when you create it).
If you have to store it, you definitely will need to use an array or other data structure (ArrayList!).
Building on the idea of scope, you -can- have the same variable name for each new BankAccount. A variable reference name isn't guaranteed to be paired with the object that it refers to. That is a convenience to the programmer, so you don't have to know the exact memory address it is being stored in.
For example:
public static void main(String[] args) {
Object o;
int i = 0;
while (i < 5) {
Object reference = new Object(); // Create a new Object and store
// it in 'reference'
o = obj; // The Object 'o' now refers to the object in 'reference'
i++;
}
System.out.println(o); // This should print information about the
// LAST object created.
}
The new Object created in the loop does not belong to 'obj'. You as a programmer use 'obj' to point to the Object. The program doesn't really know what obj means, other than the fact that it points to the Object you just created.
Finally, you can use this along with an ArrayList to make your life easier.
public static void main(String[] args) {
// Our new ArrayList to hold our objects!
ArrayList<Object> stuff = new ArrayList<Object>();
int i = 0;
while (i < 5) {
Object obj = new Object(); // Create an object and make obj point to it.
stuff.add(obj); // Put "the object that 'obj' points to" in 'stuff'.
i++;
}
// This loop goes through all of the Objects in the ArrayList and prints them
for (int index = 0; index < stuff.size(); index++) {
System.out.println(stuff.get(i)); // This will print a single
// object in the ArrayList each time.
}
}

Categories