The Artima Developer Community
Sponsored Link

Java Answers Forum
An easy question,but I don't know

17 replies on 2 pages. Most recent reply: Oct 5, 2005 9:35 PM by mausam

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 17 replies on 2 pages [ 1 2 | » ]
Weslydan

Posts: 1
Nickname: danxp
Registered: May, 2005

An easy question,but I don't know Posted: May 6, 2005 6:08 AM
Reply to this message Reply
Advertisement
public class swaps
{
public static void main(String[] arg){
int a=10;
int b=20;
swaps s=new swaps();
s.swap(a,b);
System.out.println("a="+a+"b="+b);
}
public void swap(int a,int b)
{
int t;
t=a;
a=b;
b=t;
}
}
It is compiled and run successfully,but the result is not the same as I expected,the result is "a=10,b=20"!!It did'nt change. In C language ,It can solve easily by using the pointer and the variable address. But in Java ,I can't do that,So what should I do next step???


Matthias Neumair

Posts: 660
Nickname: neumi
Registered: Sep, 2003

Re: An easy question,but I don't know Posted: May 9, 2005 1:50 AM
Reply to this message Reply
This is no easy question at all.

int is a primitive type and has no reference (pointer). Only it's value can be passed to a method.

The only way to pass a reference of a primitive type instead of it's value is to put it into an array and to pass the array like this.

public class Swaps { //Java classes should begin with a capital letter, just about everything else with a small letter.
  public static void main(String[] arg){
    int[] arr = {10, 20};
    Swaps.swap(arr); //I made the method static, so there is no need to create an instance of Swaps
    System.out.println("a="+arr[0]+"b="+arr[b]);
  }
  public static void swap(int[] arr) {
    int t = arr[0];
    arr[0] = arr[1];
    arr[1] = t;
  }
}


But if you don't store the variables in an array, it would be rather senseless, since putting the variables into the array and reading them after the operation would takte more space then writing the exchange operation into the main code.

Matthias Neumair

Posts: 660
Nickname: neumi
Registered: Sep, 2003

Re: An easy question,but I don't know Posted: May 9, 2005 1:52 AM
Reply to this message Reply
I made a mistake: arr[b] should be arr[1]

Ravi Venkataraman

Posts: 80
Nickname: raviv
Registered: Sep, 2004

Re: An easy question,but I don't know Posted: May 9, 2005 7:17 AM
Reply to this message Reply
This is an interesting problem. The original poster's code shows how object-orientation permeates the thought process and forces everything to be an object, unnecessarily so.

The swap functionality is just an action that needs to be performed. There is no state associated with the Swap object created here. It would be much better to create a utility class with a static method swap, as Matthias has done.

Additionally, Matthias's suggested solution has a swap method that returns nothing! This is counter-intuitive. Furthermore, what is the expected behaviour when the int array passed in has more than two elements? Could the developer using this expect the array to be reversed?

I'd suggest the following code

public class Util
{
   public static int[] swap(int a, int b)
   {
      int[] swappedValues = new int[2];
      int[0] = b;
      int[1] = a;
      return swappedValues;
   }
}


Much simpler is Python's tuple syntax where you can just say: a,b = b,a

Matthias Neumair

Posts: 660
Nickname: neumi
Registered: Sep, 2003

Re: An easy question,but I don't know Posted: May 10, 2005 1:42 AM
Reply to this message Reply
The problem of your solution is, that the original values remain the same.

For a lot of operation this is ok, but the sense of the method - in my opinion - is to exchange the content of 2 variables.

In your case you would have to write something like:
int[] arr = {10,20};
//(pos1)
arr = swappedValues(arr);


This would work for most cases, but not if arr at (pos1) was passed to other classes wich access it's values.

To the array problem:
We could allways use a Point object or any other class containing 2 ints.



Another question: I first thought of passing an Integer object, but then I noticed that you an't change it's value.
Is there a reason for that? I never needed it, so I never gave it a thought.

Ravi Venkataraman

Posts: 80
Nickname: raviv
Registered: Sep, 2004

Re: An easy question,but I don't know Posted: May 10, 2005 6:34 AM
Reply to this message Reply
The original problem seems simple:

What is a simple way to write a method that takes two integers and swaps them?

What we'd like to do is to write code that says something simple like: swap(a,b)

and expect the values to be swapped.


In Java, since primitives are passed by value, you have to say something like: (b,a) = swap(a,b)
instead.

In Java, you can only return one value from a method.

Hence, we are left with no alternative but to return an array of two values and expect the client code to resolve the values. I assume that the client code would never be bundled into an array in the first place; that was done merely as an artifact of the method created. Therefore, the other objection that the client code expects to pass this array to some other object will not arise.

As mentioned earlier, Python lets you do it simply by saying: b,a = a,b

Java, the language, makes it very difficult to do simple things and is very verbose, as this example illustrates.

Gregg Wonderly

Posts: 317
Nickname: greggwon
Registered: Apr, 2003

Re: An easy question,but I don't know Posted: May 15, 2005 8:18 PM
Reply to this message Reply
The object orient way of doing this is to use objects that are mutable. So, you might do

public interface Mutable<T> {
public void set(T val);
public T get();
}

public interface Swappable<T> {
public void swap(Mutable<T> v1, Mutable<T> v2);
}

and then create

public class MutableInt implements Mutable<int> {
int v;
public final void set( int val ) {
v = val;
}
public final int get() {
return v;
}
}

Then you would create your program fragment as

public class MyApp implements Swappable<int> {
MutableInt a = ...
MutableInt b = ...

public void swap( MutableInt v1, MutableInt v2 ) {
MutableInt t = new MutableInt( v1.get() );
v1.set( v2.get() );
v2.set( t.get() );
}
}

This creates the solution that doesn't use the array mechanism. In cases where these containers are not the prevalent representation of the data, I would use the arrays, because adding the classes doesn't help solidify the programming paradigms of the application. But, if there are values which are mutable, and which have many different presenses in the application, you will find that these additional objects are no different in overhead than the use of the array.

Ravi Venkataraman

Posts: 80
Nickname: raviv
Registered: Sep, 2004

Re: An easy question,but I don't know Posted: Sep 7, 2005 7:01 AM
Reply to this message Reply
Gregg said, "The object orient way of doing this is ..."

That is the whole point. Why must everything be Object Oriented? For re-use? Libraries for mathematical functions are probably the most reused code in existence. Are they object oriented? Not at all!

Look at the problem that needs to be solved: swapping two integers. Python provides a nice, easy way to do so:

(b.a) = (a,b)

Look at the scaffolding you have created to solve such a simple problem. Why do you need three classes including 2 interfaces? Why can not a simple static method in a utility class do the job?

And you'd probably create a MutableChar class, MutableByte class, etc. If this is what you mean by being Object Oriented, call me unconvinced of the power of OO.

Ravi

SRV001

Posts: 13
Nickname: srv001
Registered: May, 2004

Re: An easy question,but I don't know Posted: Sep 7, 2005 1:23 PM
Reply to this message Reply
Just thought that I'd throw my two cents worth in:

Of course you can do this in C quite easily, but remember that Java is pass by value only. That is why your method didn't work. It copied the values into your method and then they went out of scope after the swap method completed.

If you pass in an Object reference you cannot change the object reference while in the method, but you can call methods inside the Object such as setXXX and getXXX. Just remember that there is always another way (and the Java way is usually simpler).

I believe that the aim of the C Swap program was just a demonstration in how to use pointers or references anyway.

public class Swap
{
    public static void main(String[] args)
    {
        Swap s = new Swap();
        Point p = new Point(25, 40);
 
        System.out.println("x = " + p.getX() + ", y = " + p.getY());
 
        s.swap(p);
 
        System.out.println("x = " + p.getX() + ", y = " + p.getY());
    }
 
    public void swap(Point p)
    {
        int temp;
 
        temp = p.getX();
        p.setX(p.getY());
        p.setY(temp);
    }
}
 
public class Point
{
    private int x;
    private int y;
 
    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
 
    public void setX(int x) {
        this.x = x;
    }
 
    public void setY(int y) {
        this.y = y;
    }
 
    public int getX() {
        return this.x;
    }
 
    public int getY() {
        return this.y;
    }
}

SRV001

Posts: 13
Nickname: srv001
Registered: May, 2004

Re: An easy question,but I don't know Posted: Sep 7, 2005 1:30 PM
Reply to this message Reply
One more...

public class Swap2
{
    int x;
    int y;
 
    public static void main(String[] args)
    {
        Swap2 s = new Swap2();
 
        s.x = 25;
        s.y = 40;
 
        System.out.println("x = " + s.x + ", y = " + s.y);
 
        s.swap();
 
        System.out.println("x = " + s.x + ", y = " + s.y);
    }
 
    public void swap()
    {
        int temp;
 
        temp = x;
        x = y;
        y = temp;
    }
}

Matthias Neumair

Posts: 660
Nickname: neumi
Registered: Sep, 2003

Re: An easy question,but I don't know Posted: Sep 7, 2005 10:19 PM
Reply to this message Reply
All these solutions are nice, but fact is, that you can't swap the content of two primitive variables passing them to a method. You allways have to pass the "container" of those variables.

Above there was a Question "why must it be object oriented?"

Well, Java follows the "object oriented rules" more close than any other programming language except SmallTalk (wich knows ony 2 primitive types Num and Char and does not allow to modify objects from the outside).

The good thing on Java is that you have allmost no possibility to program non-object oriented code.

That you actually can pass primitive variables to a method is not object oriented, but it would be too much of work to wrap every primitive variable.

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: An easy question,but I don't know Posted: Sep 8, 2005 9:02 PM
Reply to this message Reply
> I believe that the aim of the C Swap program was just a demonstration
> in how to use pointers or references anyway.

My first exposure to swap() in C was in implementing sorting algorithms. If that is the slant in a similar Java exercise, then your swap() would probably look like this:
static void swap( int [] array, int index1, int index2 )
{
   int temp = array[index1];
   array[index1] = array[index2];
   array[index2] = temp;
}

(disregarding cleverness with XOR-ing, of course)

Jeff Thomson

Posts: 14
Nickname: thomson
Registered: Sep, 2005

Re: An easy question,but I don't know Posted: Sep 14, 2005 5:28 AM
Reply to this message Reply
Similar threads with some more ways to attain the solution

http://forum.java.sun.com/thread.jspa?threadID=584778&tstart=0
http://forum.java.sun.com/thread.jspa?threadID=579439&messageID=2931217
http://forum.java.sun.com/thread.jspa?forumID=31&threadID=295413

----------------
Jeff Thomson
http://www.devsquare.com
Online Application Development

Wentao Tang

Posts: 1
Nickname: dfjskfj
Registered: Sep, 2005

Re: An easy question,but I don't know Posted: Sep 14, 2005 8:18 AM
Reply to this message Reply
My version:encapsulate a b in class.And use Key "this" in swap
//
public class Swaps{
private static int a=10;
private static int b=20;
public static void main(String[] arg){

Swaps s=new Swaps();
s.swap();
System.out.println("a="+a+" b="+b);
}
public void swap_ab(){
int t;
t=this.a;
this.a=this.b;
this.b=t;
}
}///:~

Matt Gerrans

Posts: 1153
Nickname: matt
Registered: Feb, 2002

Re: An easy question,but I don't know Posted: Sep 14, 2005 11:58 AM
Reply to this message Reply
You're joking, right?

Flat View: This topic has 17 replies on 2 pages [ 1  2 | » ]
Topic: JSP - linking in domino:formlink Previous Topic   Next Topic Topic: Kanji input in text box

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use