Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

wrapper class

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how can i swap values of two integer class by using a functiion.
i.e class swap{
public static void main{
integer i=new integer(2);
integer j=new integer(5)
swap(i,j)
System.out.println(i+ " " +j);
}
swap(integer i,integer j)
{
}
 
Jesper Ottosson
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper- I don't think that will do it. See what happens when you test it:
<code><pre>class Test {
public void swap(Integer i, Integer j){
int temp = i.intValue();
i = new Integer(j.intValue());
j = new Integer(temp);
}
public static void main(String[] args) {
Integer a = new Integer(1);
Integer b = new Integer(2);
System.out.println("a: " + a);
System.out.println("b: " + b);
new Test().swap(a, b);
System.out.println("a: " + a);
System.out.println("b: " + b);
}
}</pre></code>
The key is that i and j are variables local to swap(). They start out pointing to the same arrays as a and b, but when you reassign them that has no effect on a and b.
Praveen- this isn't really possible in Java. To swap two values, a method has to have access not to the values themselves, but to an object or objects which contain the values. Unfortunately wrapper classes don't work for this because they are immutable - there are no methods which allow you to change the value within a given Integer. As an alternative though, here's a way you can swap two members of an int array:
<code><pre> public void swap(int[] array, int index1, int index2){
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}<pre></code>
 
Betty Reynolds
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or you can use my favorite object types strings/stringbuffers (there are almost no types that you can't convert to or between using using these classes). For example:

There are a number of ways to do it using these objects.



[This message has been edited by Betty Reynolds (edited April 08, 2000).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic