如何用 Java 编写基本的交换函数

发布于 2024-09-16 15:06:00 字数 150 浏览 9 评论 0原文

我是java新手。如何编写与以下 C 代码等效的 java 代码。

void Swap(int *p, int *q)
{
   int temp;
   temp = *p;
   *p = *q;
   *q = temp;
} 

I am new to java. How to write the java equivalent of the following C code.

void Swap(int *p, int *q)
{
   int temp;
   temp = *p;
   *p = *q;
   *q = temp;
} 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

不疑不惑不回忆 2024-09-23 15:06:05
  class Swap2Values{
    public static void main(String[] args){
       int a = 20, b = 10;

       //before swaping
       System.out.print("Before Swapping the values of a and b are: a = "+a+", b = "+b);

       //swapping
       a = a + b;
       b = a - b;
       a = a - b;

       //after swapping
      System.out.print("After Swapping the values of a and b are: a = "+a+", b = "+b);
    }
  }
  class Swap2Values{
    public static void main(String[] args){
       int a = 20, b = 10;

       //before swaping
       System.out.print("Before Swapping the values of a and b are: a = "+a+", b = "+b);

       //swapping
       a = a + b;
       b = a - b;
       a = a - b;

       //after swapping
      System.out.print("After Swapping the values of a and b are: a = "+a+", b = "+b);
    }
  }
爱本泡沫多脆弱 2024-09-23 15:06:04

Java是按值传递的。所以你所说的交换是不可能的。但是您可以交换两个对象的内容,也可以内联进行。

Java is pass by value. So the swap in the sense you mean is not possible. But you can swap contents of two objects or you do it inline.

z祗昰~ 2024-09-23 15:06:04

您可以使用或不使用临时变量来交换变量。

这是一篇文章,提供了多种方法来交换没有临时变量的数字:

http://topjavatutorial.com/java/java-programs/swap-two-numbers-without-a-temporary-variable-in-java/

You can swap variables with or without using a temporary variable.

Here is an article that provides multiple methods to swap numbers without temp variable :

http://topjavatutorial.com/java/java-programs/swap-two-numbers-without-a-temporary-variable-in-java/

心在旅行 2024-09-23 15:06:04

您可以轻松地自己编写一个。

给定:

int array[]={1,2};

你做:

int temp=array[0];
array[0]=array[1];
array[1]=temp;

你就完成了。 3行代码。

You can easily write one yourself.

given:

int array[]={1,2};

you do:

int temp=array[0];
array[0]=array[1];
array[1]=temp;

And you're done. 3 lines of code.

梦回梦里 2024-09-23 15:06:04

在 java 中使用指针进行交换是不可能的。 但是,您可以通过传递包含两个对象的数组来实现交换。

代码如下:

public class Swap {
    public static void swap(String [] a){
        String temp;
        temp = a[0];
        a[0] = a[1];
        a[1] = temp;
    }
    public static void main(String [] args){
        String [] foo = new String[2];
        foo[0] = "str1";
        foo[1] = "str2";
        swap(foo);
        System.out.println("First value: "+ foo[0]);
        System.out.println("Second value: "+ foo[1]);
    }
}

输出:

First value: str2
Second value: str1

Swapping by using pointer is not possible in java. However, you can implement swapping by passing array containing two objects.

Code goes like this:

public class Swap {
    public static void swap(String [] a){
        String temp;
        temp = a[0];
        a[0] = a[1];
        a[1] = temp;
    }
    public static void main(String [] args){
        String [] foo = new String[2];
        foo[0] = "str1";
        foo[1] = "str2";
        swap(foo);
        System.out.println("First value: "+ foo[0]);
        System.out.println("Second value: "+ foo[1]);
    }
}

Output:

First value: str2
Second value: str1
ヤ经典坏疍 2024-09-23 15:06:04
public class swaptemp {
    public static void main(String[] args) {
        String s1="10";
        String s2="20";
        String temp;
        System.out.println(s1);
        System.out.println(s2);

        temp=Integer.toString(Integer.parseInt(s1));
        s1=Integer.toString(Integer.parseInt(s2));
        s2=Integer.toString(Integer.parseInt(temp));

        System.out.println(s1);
        System.out.println(s2);
    }
}
public class swaptemp {
    public static void main(String[] args) {
        String s1="10";
        String s2="20";
        String temp;
        System.out.println(s1);
        System.out.println(s2);

        temp=Integer.toString(Integer.parseInt(s1));
        s1=Integer.toString(Integer.parseInt(s2));
        s2=Integer.toString(Integer.parseInt(temp));

        System.out.println(s1);
        System.out.println(s2);
    }
}
轻拂→两袖风尘 2024-09-23 15:06:04
//here is also another answer:
class SwapDemo{
    static int a=1, b=2 ;
    public static void main(String [] args){
        Swap swp = new Swap();
        swp.swaps(x,y);
        System.out.println( " a (was 1)now is " + a + " b (was 2) now is " + b);
    }
}
class Swap{
    void swaps(int c, int d){
            SwapDemo f = new SwapDemo();
            f.a = c;
            f.a = d;
        }
}
//here is also another answer:
class SwapDemo{
    static int a=1, b=2 ;
    public static void main(String [] args){
        Swap swp = new Swap();
        swp.swaps(x,y);
        System.out.println( " a (was 1)now is " + a + " b (was 2) now is " + b);
    }
}
class Swap{
    void swaps(int c, int d){
            SwapDemo f = new SwapDemo();
            f.a = c;
            f.a = d;
        }
}
叹倦 2024-09-23 15:06:03

在这种情况下,有一种快速而肮脏的解决方案,即使用具有一个元素的数组:

public void swap(int[] a, int[] b) {
  int temp = a[0];
  a[0] = b[0];
  b[0] = temp;
}

当然,您的代码也必须使用这些数组,这是不方便的。如果您想从内部类修改局部最终变量,则数组技巧更有用:

public void test() {
  final int[] a = int[]{ 42 };  
  new Thread(new Runnable(){ public void run(){ a[0] += 10; }}).start();
  while(a[0] == 42) {
    System.out.println("waiting...");   
  }
  System.out.println(a[0]);   
} 

In cases like that there is a quick and dirty solution using arrays with one element:

public void swap(int[] a, int[] b) {
  int temp = a[0];
  a[0] = b[0];
  b[0] = temp;
}

Of course your code has to work with these arrays too, which is inconvenient. The array trick is more useful if you want to modify a local final variable from an inner class:

public void test() {
  final int[] a = int[]{ 42 };  
  new Thread(new Runnable(){ public void run(){ a[0] += 10; }}).start();
  while(a[0] == 42) {
    System.out.println("waiting...");   
  }
  System.out.println(a[0]);   
} 
绅刃 2024-09-23 15:06:03

那么强大的IntHolder呢?我就是喜欢任何名称中带有“天哪”的包装!

import org.omg.CORBA.IntHolder;

IntHolder a = new IntHolder(p);
IntHolder b = new IntHolder(q);

swap(a, b);

p = a.value;
q = b.value;

void swap(IntHolder a, IntHolder b) {
    int temp = a.value;
    a.value = b.value;
    b.value = temp;
}

What about the mighty IntHolder? I just love any package with omg in the name!

import org.omg.CORBA.IntHolder;

IntHolder a = new IntHolder(p);
IntHolder b = new IntHolder(q);

swap(a, b);

p = a.value;
q = b.value;

void swap(IntHolder a, IntHolder b) {
    int temp = a.value;
    a.value = b.value;
    b.value = temp;
}
一笑百媚生 2024-09-23 15:06:03

Snippet-1

public int[] swap1(int[] values) {
  if (values == null || values.length != 2)
    throw new IllegalArgumentException("parameter must be an array of size 2");
  int temp = values[0];
  values[0]=values[1];
  values[1]=temp;
  return values;
}

Snippet-2

public Point swap2(java.awt.Point p) {
  if (p == null)
    throw new NullPointerException();
  int temp = p.x;
  p.x = p.y;
  p.y = temp;
  return p;
}

用法:

int[] values = swap1(new int[]{x,y});
x = values[0];
y = values[1];

Point p = swap2(new Point(x,y));
x = p.x;
y = p.y;

Snippet-1

public int[] swap1(int[] values) {
  if (values == null || values.length != 2)
    throw new IllegalArgumentException("parameter must be an array of size 2");
  int temp = values[0];
  values[0]=values[1];
  values[1]=temp;
  return values;
}

Snippet-2

public Point swap2(java.awt.Point p) {
  if (p == null)
    throw new NullPointerException();
  int temp = p.x;
  p.x = p.y;
  p.y = temp;
  return p;
}

Usage:

int[] values = swap1(new int[]{x,y});
x = values[0];
y = values[1];

Point p = swap2(new Point(x,y));
x = p.x;
y = p.y;
北方的巷 2024-09-23 15:06:03

Java 使用按值传递。使用方法不可能交换两个基元或对象

尽管可以交换整数数组中的两个元素。

Java uses pass-by-value. It is not possible to swap two primitives or objects using a method.

Although it is possible to swap two elements in an integer array.

新雨望断虹 2024-09-23 15:06:03

您不能在 Java 中使用引用,因此不可能使用交换函数,但您可以在每次使用交换操作时使用以下代码片段:

T t = p
p = q
q = t

其中 T 是 p 和 q 的类型

但是,可以通过重写属性来交换可变对象:

void swap(Point a, Point b) {
  int tx = a.x, ty = a.y;
  a.x = b.x; a.y = b.y;
  b.x = t.x; b.y = t.y;
}

You cannot use references in Java, so a swap function is impossible, but you can use the following code snippet per each use of swap operations:

T t = p
p = q
q = t

where T is the type of p and q

However, swapping mutable objects may be possible by rewriting properties:

void swap(Point a, Point b) {
  int tx = a.x, ty = a.y;
  a.x = b.x; a.y = b.y;
  b.x = t.x; b.y = t.y;
}
梦幻之岛 2024-09-23 15:06:03

你必须内联完成。但在 Java 中你确实不需要这种交换。

You have to do it inline. But you really don't need that swap in Java.

暮年慕年 2024-09-23 15:06:03

你的交换函数本质上是改变两块内存中的值。任何引用这些内存位的内容现在都将获得不同的值。

在 Java 中并没有真正的指针,所以这是行不通的。相反,引用保存在对象上,并且您只能更改对象内部的内容。如果您需要在两个位置引用一个对象,以便可以在系统中传递相同的值并使事物对它们的变化做出反应,请尝试类似 存储库模式依赖注入

我们只能猜测为什么你需要用 C 编写这段代码。我能给出的唯一建议是考虑对你想要实现的对象的更改,最好在实际对象上添加一个方法,而不是拉出它们的内部结构,并且而是调用该方法。如果这对您没有帮助,请尝试发布调用代码,因为我们可能会很好地了解如何以 Java 方式解决实际问题。

Your swap function is essentially changing the values in two pieces of memory. Anything referencing those bits of memory will now get different values.

In Java there aren't really pointers, so this won't work. Instead, references are held on objects, and you can only change stuff inside the objects. If you need to reference one object in two places, so that you can pass the same values around the system and have things react to them changing, try something like the repository pattern or dependency injection.

We can only guess at why you needed this code in C. The only advice I can give is to think about the changes to the objects which you want to achieve, preferably add a method on the actual objects rather than pulling their internals out, and call that method instead. If this doesn't help you, try posting the calling code as we'll probably have a good idea of how to solve the real problem Java-style.

一笔一画续写前缘 2024-09-23 15:06:02

这里有一个技巧:

public static int getItself(int itself, int dummy)
{
    return itself;
}

public static void main(String[] args)
{
    int a = 10;
    int b = 20;

    a = getItself(b, b = a);
}

Here is one trick:

public static int getItself(int itself, int dummy)
{
    return itself;
}

public static void main(String[] args)
{
    int a = 10;
    int b = 20;

    a = getItself(b, b = a);
}
七婞 2024-09-23 15:06:02

对两个整数进行排序

简短的答案是:你不能这样做,java 没有指针。

但您可以执行类似的操作:

public void swap(AtomicInteger a, AtomicInteger b){
    // look mom, no tmp variables needed
    a.set(b.getAndSet(a.get()));
}

您可以使用所有类型的容器对象(例如集合和数组或具有 int 属性的自定义对象)执行此操作,但不能使用基元及其包装器(因为它们都是不可变的)。但我想,使它成为单行的唯一方法是使用 AtomicInteger。

顺便说一句:如果您的数据恰好是列表,更好的交换方法是使用 Collections.swap(List, int, int)

Swaps the elements at the specified positions in the specified list.
(If the specified positions are equal, invoking this method leaves
the list unchanged.)

Parameters:
    list - The list in which to swap elements.
    i - the index of one element to be swapped.
    j - the index of the other element to be swapped. 

对 int[] 数组进行排序

显然真正的目标是对整数数组进行排序。
这是一行 Arrays.sort(int[])

int[] arr = {2,3,1,378,19,25};
Arrays.sort(arr);

检查输出:

System.out.println(Arrays.toString(arr));
// [1, 2, 3, 19, 25, 378]

这是一个简单的辅助函数,用于交换整数数组中的两个位置:

public static void swap(final int[] arr, final int pos1, final int pos2){
    final int temp = arr[pos1];
    arr[pos1] = arr[pos2];
    arr[pos2] = temp;
}

Sorting two ints

The short answer is: you can't do that, java has no pointers.

But here's something similar that you can do:

public void swap(AtomicInteger a, AtomicInteger b){
    // look mom, no tmp variables needed
    a.set(b.getAndSet(a.get()));
}

You can do this with all kinds of container objects (like collections and arrays or custom objects with an int property), but just not with primitives and their wrappers (because they are all immutable). But the only way to make it a one-liner is with AtomicInteger, I guess.

BTW: if your data happens to be a List, a better way to swap is to use Collections.swap(List, int, int):

Swaps the elements at the specified positions in the specified list.
(If the specified positions are equal, invoking this method leaves
the list unchanged.)

Parameters:
    list - The list in which to swap elements.
    i - the index of one element to be swapped.
    j - the index of the other element to be swapped. 

Sorting an int[] array

apparently the real objective is to sort an array of ints.
That's a one-liner with Arrays.sort(int[]):

int[] arr = {2,3,1,378,19,25};
Arrays.sort(arr);

To check the output:

System.out.println(Arrays.toString(arr));
// [1, 2, 3, 19, 25, 378]

And here is a simple helper function to swap two positions in an array of ints:

public static void swap(final int[] arr, final int pos1, final int pos2){
    final int temp = arr[pos1];
    arr[pos1] = arr[pos2];
    arr[pos2] = temp;
}
但可醉心 2024-09-23 15:06:02

下面是一种使用按位XOR(^) 运算符在java 中在一行中交换两个变量的方法。

class Swap
{
   public static void main (String[] args)
   {
      int x = 5, y = 10;
      x = x ^ y ^ (y = x);
      System.out.println("New values of x and y are "+ x + ", " + y);
   }
} 

输出:

x 和 y 的新值为 10、5

Here's a method to swap two variables in java in just one line using bitwise XOR(^) operator.

class Swap
{
   public static void main (String[] args)
   {
      int x = 5, y = 10;
      x = x ^ y ^ (y = x);
      System.out.println("New values of x and y are "+ x + ", " + y);
   }
} 

Output:

New values of x and y are 10, 5

荒岛晴空 2024-09-23 15:06:02

将此单行代码用于任何原始数字类,包括 doublefloat

a += (b - (b = a));

例如:

double a = 1.41;
double b = 0;
a += (b - (b = a));
System.out.println("a = " + a + ", b = " + b);

输出为 a = 0.0, b = 1.41

Use this one-liner for any primitive number class including double and float:

a += (b - (b = a));

For example:

double a = 1.41;
double b = 0;
a += (b - (b = a));
System.out.println("a = " + a + ", b = " + b);

Output is a = 0.0, b = 1.41

随波逐流 2024-09-23 15:06:02

Java 中没有指针。但是,“包含”对象的每个变量都是对该对象的引用。要具有输出参数,您必须使用对象。 在你的例子中,是 Integer 对象。

因此,你必须创建一个包含整数的对象,并更改该整数。您不能使用 Integer 类,因为它是不可变的(即它的值不能更改)。

另一种方法是让该方法返回一个数组或一对整数。

There are no pointers in Java. However, every variable that "contains" an object is a reference to that object. To have output parameters, you would have to use objects. In your case, Integer objects.

So you would have to make an object which contains an integer, and change that integer. You can not use the Integer class, since it is immutable (i.e. its value cannot be changed).

An alternative is to let the method return an array or pair of ints.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文