Hack Forums
[Java] How do I swap object references in java? - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [Java] How do I swap object references in java? (/showthread.php?tid=5416772)



How do I swap object references in java? - Мишка - Sep 26, 2016

need to know how to do this for a friend, he said he searched for a tut but couldn't find anything he needed to do so, let me know!


* - Jire - Sep 26, 2016

Code
Object example = new Object(); // old reference
example = new Object(); // new reference



* - Мишка - Sep 26, 2016

(Sep 26, 2016 11:06 AM)⚔⚔⚔⚔⚔ Wrote:  
Code
Object example = new Object(); // old reference
example = new Object(); // new reference


Code
Object tempObj = obj1;
obj1 = obj2;
obj2 = tempObj;
System.out.println("Objects switched");

he tried this but it wont work showing an as example


* - minimalist - Sep 26, 2016

(Sep 26, 2016 11:16 AM)Мишка Wrote:  
Code
Object tempObj = obj1;
obj1 = obj2;
obj2 = tempObj;
System.out.println("Objects switched");

he tried this but it wont work showing an as example

That's because he's making references to an object and variables that don't exist; should be:
Code
public static void main (String[] args) {
Object tempObj = new Object();
Object obj1 = new Object();
Object obj2 = new Object();
obj1 = obj2;
obj2 = tempObj;
System.out.println("Objects switched");
}
class Object {
public void Object() {
...code here
}
}



* - Stealth™ - Sep 26, 2016

(Sep 26, 2016 11:36 AM)Minimalist Wrote:  That's because he's making references to an object and variables that don't exist; should be:
Code
public static void main (String[] args) {
Object tempObj = new Object();
Object obj1 = new Object();
Object obj2 = new Object();
obj1 = obj2;
obj2 = tempObj;
System.out.println("Objects switched");
}
class Object {
public void Object() {
...code here
}
}

The Object class already exists (java.lang.Object), so you don't need another class for it.

But OP, you provided the correct solution yourself.


* - Мишка - Sep 26, 2016

thank you guys for your help! appreciate it :)