How to swap two primitive dataelements using swap function?

How to write a swap function that can swap two integer..?
[64 byte] By [chandra.ta] at [2007-10-3 6:44:47]
# 1
Is this home work?To my knoledge there is no such thing in Java API called swap function. If you need a method to swap two value you will have to write it.
LRMKa at 2007-7-15 1:34:28 > top of Java-index,Java Essentials,Java Programming...
# 2
Hey, i know that...? My question how to do that? Do u have any idea?
chandra.ta at 2007-7-15 1:34:28 > top of Java-index,Java Essentials,Java Programming...
# 3

int a =1;

int b =2;

void swap() {

int tmp = a;

a = b;

b = tmp;

}

I have a feeling that this won't satisfy the OP.

orbacha at 2007-7-15 1:34:28 > top of Java-index,Java Essentials,Java Programming...
# 4
u r right, once the control leaves the function the values are reset...! this wont work..!
chandra.ta at 2007-7-15 1:34:28 > top of Java-index,Java Essentials,Java Programming...
# 5
No, the values won't be reset. What makes you think so?
orbacha at 2007-7-15 1:34:28 > top of Java-index,Java Essentials,Java Programming...
# 6
jst dont make them global... jst pass them to the function..!
chandra.ta at 2007-7-15 1:34:28 > top of Java-index,Java Essentials,Java Programming...
# 7
> jst dont make them global... jst pass them to the> function..!I have an idea. Why don't you post some code that demonstrates how you think it should be done?
orbacha at 2007-7-15 1:34:28 > top of Java-index,Java Essentials,Java Programming...
# 8

class Test

{

public static void main(String vec[])

{

int i=10,j=20;

system.out.println(i+" "+j);

swap(i,j); // swap them....

system.out.println(i+" "+j);

}

void swap(int i, int j)

{

int k;

k=j;

j=i;

i=k;

}

};

you cant swap i,j using the above code... so how to do that? that was my question..!

chandra.ta at 2007-7-15 1:34:28 > top of Java-index,Java Essentials,Java Programming...
# 9

Now we are getting somewhere. Next time you post code, use the code tags!! See Formatting Tips or just select the code and click the Code button.

> you cant swap i,j using the above code...

You're right. You can't do that.

> so how to do that?

The ints must be within some object, like I showed you

You cannot swap the values of two arguments to a method and expect the caller's variables be swapped because Java passes arguments by value not reference. There is no such thing as a pointer to a variable in Java as there is in C/C++.

orbacha at 2007-7-15 1:34:28 > top of Java-index,Java Essentials,Java Programming...
# 10
jst please give me the code for that. i know we can use wrapper classes. but how to do that? give me some sample code..!
chandra.ta at 2007-7-15 1:34:28 > top of Java-index,Java Essentials,Java Programming...
# 11

I thought I already gave you the code. Here it is, completely digested for you:

public Class Swap {

public int a;

public int b;

public void swap() {

int tmp = a;

a = b;

b = tmp;

}

}

orbacha at 2007-7-15 1:34:28 > top of Java-index,Java Essentials,Java Programming...
# 12
@OP: I hope you are aware that there is no pass-by-reference in Java (as we keep telling people four times a week)...
CeciNEstPasUnProgrammeura at 2007-7-15 1:34:28 > top of Java-index,Java Essentials,Java Programming...
# 13

this will swap the data elements, that belong to the swap class only..! right..?

what if i need a generic swap function that can swap 2 integers..?

example::

class Test

{

Swaps var = new Swaps();

int i=10,j=20;

//print

var.swap(i,j);

//print

}

class Swaps

{

void swap(int i, int j)

{

}

}

chandra.ta at 2007-7-15 1:34:28 > top of Java-index,Java Essentials,Java Programming...
# 14
> what if i need a generic swap function that can swap> 2 integers..?See reply 12.
CeciNEstPasUnProgrammeura at 2007-7-15 1:34:28 > top of Java-index,Java Essentials,Java Programming...
# 15

> this will swap the data elements, that belong to the

> swap class only..! right..?

>

> what if i need a generic swap function that can swap

> 2 integers..?

> example::

>

> class Test

> {

> Swaps var = new Swaps();

> int i=10,j=20;

>

> //print

> var.swap(i,j);

> //print

> }

>

> class Swaps

> {

> void swap(int i, int j)

> {

> }

> }

You can't do that in Java for the reasons already given.

orbacha at 2007-7-21 11:40:31 > top of Java-index,Java Essentials,Java Programming...
# 16
then what is the use os wrapper classes..? if there is a no way? What do u mean by a wrapper..? an integer wrapped in an object? so in an object of type Integer, there should be an int (integer)..! how to access that?
chandra.ta at 2007-7-21 11:40:31 > top of Java-index,Java Essentials,Java Programming...
# 17

> then what is the use os wrapper classes..?

What is "os wrapper"?

> if there is a no way?

You know, really nobody writes a utility method to swap variables.

> What do u mean by a wrapper..? an

> integer wrapped in an object?

By wrapper he meant the Swap class he posted. A wrapper around your pair of variables.

> so in an object of

> type Integer, there should be an int (integer)..!

There might be. There doesn't have to be. It could as well store it in a String. You are not supposed to know.

> how to access that?

Not at all. you ask the instance to send you its int value using getIntValue(). How it does that is again none of your business.

CeciNEstPasUnProgrammeura at 2007-7-21 11:40:31 > top of Java-index,Java Essentials,Java Programming...
# 18

> then what is the use os wrapper classes..? if there

> is a no way? What do u mean by a wrapper..? an

> integer wrapped in an object? so in an object of

> type Integer, there should be an int (integer)..! how

> to access that?

chandra. If class Integer was not final then you could define your "ints" as Integer objects and swap would work. But Integer is final and cannot be reassigned to it. You could write your own MyInteger class then you could do:

MyInteger a = new MyInteger(1);

MyInteger b = new MyInteger(2);

// a=1 ; b=2

swap(a, b);

// a=2; b=1

void swap(MyInteger i, MyInteger j) {

int tmp = i.getInt();

i.setInt(j.getInt());

j.setInt(tmp);

}

But now a and b are not int, they are references to objects of type MyInteger. You cannot swap variables of type int by passing them as args to a method.

orbacha at 2007-7-21 11:40:31 > top of Java-index,Java Essentials,Java Programming...
# 19
hi orbach,your answer convincing. Is there any way that we can access the underlying int, using the Integer object? if so let me know.
chandra.ta at 2007-7-21 11:40:31 > top of Java-index,Java Essentials,Java Programming...
# 20
hi orbach thank you. i got it..!
chandra.ta at 2007-7-21 11:40:31 > top of Java-index,Java Essentials,Java Programming...
# 21
> hi orbach,> your answer convincing. Is there any way that we can> access the underlying int, using the Integer object?> if so let me know.You could use Reflection but why bother? Create your own Integer class like I described.
orbacha at 2007-7-21 11:40:31 > top of Java-index,Java Essentials,Java Programming...
# 22
> hi orbach > thank you. i got it..!Cool :-)-o-
orbacha at 2007-7-21 11:40:31 > top of Java-index,Java Essentials,Java Programming...
# 23
> chandra. If class Integer was not final then you> could define your "ints" as Integer objects and swap> would work. But Integer is final and cannot be> reassigned to it. Immutability has nothing to do with classes being declared "final".
CeciNEstPasUnProgrammeura at 2007-7-21 11:40:31 > top of Java-index,Java Essentials,Java Programming...
# 24

> hi orbach,

> your answer convincing. Is there any way that we can

> access the underlying int, using the Integer object?

> if so let me know.

What makes you sure that there is an underlying int? It's an implementation detail nobody's supposed to worry about since it'll only lead to tightly coupled code. You should program to an interface, not to an implementation.

CeciNEstPasUnProgrammeura at 2007-7-21 11:40:31 > top of Java-index,Java Essentials,Java Programming...
# 25

> > hi orbach,

> > your answer convincing. Is there any way that we

> can

> > access the underlying int, using the Integer

> object?

> > if so let me know.

>

> You could use Reflection but why bother?

Because that way you can completely fsck up your runtime, as some Integers are pooled since Java 5. :) It's easy to use Reflection to modify the value of Integer(0) to 1, with the result that (List<Integer>.get(x) == 0) will never be true.

CeciNEstPasUnProgrammeura at 2007-7-21 11:40:31 > top of Java-index,Java Essentials,Java Programming...
# 26
> Immutability has nothing to do with classes being> declared "final".True, I meant the underlying value of Integer is final.
orbacha at 2007-7-21 11:40:31 > top of Java-index,Java Essentials,Java Programming...
# 27

> What makes you sure that there is an underlying int?

> It's an implementation detail nobody's supposed to

> worry about since it'll only lead to tightly coupled

> code. You should program to an interface, not to an

> implementation.

There are many reasons against using Reflection for this purpose. This is one. Instead of saying "I wouldn't bother" I should've said "I don't recommend it".

orbacha at 2007-7-21 11:40:31 > top of Java-index,Java Essentials,Java Programming...
# 28

> Because that way you can completely fsck up your

> runtime, as some Integers are pooled since Java 5. :)

> It's easy to use Reflection to modify the value of

> Integer(0) to 1, with the result that

> (List<Integer>.get(x) == 0) will never be true.

Bit twiddling, understood. I wasn't recommending using Reflection as a solution. More in the sense of: "Reflection could give you access but don't". Without going into the reasons against using Reflection, which you well are pointing out.

[edit] The Bit Twiddling comment is BS. Please ignore. [/edit]

Message was edited by:

orbach

orbacha at 2007-7-21 11:40:31 > top of Java-index,Java Essentials,Java Programming...
# 29

> There are many reasons against using Reflection for

> this purpose. This is one. Instead of saying "I

> wouldn't bother" I should've said "I don't recommend

> it".

I didn't mean to criticise you. I was just providing an example supporting your statement. Another reason is that as soon as you start using reflection, you usually have moved pretty far away from good and reliable OO design.

CeciNEstPasUnProgrammeura at 2007-7-21 11:40:31 > top of Java-index,Java Essentials,Java Programming...
# 30

> I didn't mean to criticise you. I was just providing

> an example supporting your statement. Another reason

> is that as soon as you start using reflection, you

> usually have moved pretty far away from good and

> reliable OO design.

no problem at all, I was really criticising myself. There may be some exceptional circumstances where Reflection may be used IMHO. As in "there are exceptions to every rule". But I agree with you in essence.

orbacha at 2007-7-21 11:40:36 > top of Java-index,Java Essentials,Java Programming...
# 31

Here's a crude way of swaping two Integers:

package com;

public class Test {

public static void main(String[] args) {

StringBuffer val1 = new StringBuffer("-100");

StringBuffer val2 = new StringBuffer("20");

swap(val1, val2);

System.out.println("Val 1 : " + val1);

System.out.println("Val 2 : " + val2);

}

public static void swap(StringBuffer val1, StringBuffer val2) {

val1.append("~" + val2);

val2.append("~" + val1.substring(0,val1.indexOf("~")));

val1.delete(0 , val1.indexOf("~")+1);

val2.delete(0 , val2.indexOf("~")+1);

}

}

shyam_nata at 2007-7-21 11:40:36 > top of Java-index,Java Essentials,Java Programming...
# 32

>Here's a crude way of swaping two Integers:

Not only is that crude, but .. nevermind.

/**

* @since October 16, 2006, 12:39 PM

* @author Ian Schneider

*/

public class SwapInteger {

static void swap(int[] ints) {

int t = ints[0];

ints[0] = ints[1];

ints[1] = t;

}

public static void main(String[] args) throws Exception {

int[] stuff = {1,2};

swap(stuff);

System.out.println(stuff[0] + "," + stuff[1]);

}

}

IanSchneidera at 2007-7-21 11:40:36 > top of Java-index,Java Essentials,Java Programming...
# 33

> Because that way you can completely fsck up your

> runtime, as some Integers are pooled since Java 5. :)

> It's easy to use Reflection to modify the value of

> Integer(0) to 1, with the result that

> (List<Integer>.get(x) == 0) will never be true.

Ooohhh fun! I never even thought of that!

jschella at 2007-7-21 11:40:36 > top of Java-index,Java Essentials,Java Programming...
# 34

> Ooohhh fun! I never even thought of that!

You don't know the infamous rubber chicken?

import java.lang.reflect.*;

public class MyMathTeacherLied {

public static void main(String[] args) throws Exception {

VoodooMagic.shakeRubberChicken();

if (Integer.valueOf(0) == 1) System.out.println("WTF!");

}

}

class VoodooMagic {

static void shakeRubberChicken() throws Exception{

Class cls = Integer.class;

Field field = cls.getDeclaredField("value");

field.setAccessible(true);

field.set(0, 1);

}

}

If you do that in an environment I have to debug, I'll roast your nuts on a spit.

CeciNEstPasUnProgrammeura at 2007-7-21 11:40:36 > top of Java-index,Java Essentials,Java Programming...
# 35
thanks for the visual
tsitha at 2007-7-21 11:40:36 > top of Java-index,Java Essentials,Java Programming...