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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3624525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 02:49:04  来源:igfitidea点击:

How to write a basic swap function in Java

javaswap

提问by Melinda

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

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

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

回答by Sjoerd

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

Java 中没有指针。但是,“包含”一个对象的每个变量都是对该对象的引用。要获得输出参数,您必须使用对象。在您的情况下, Integer 对象。

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).

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

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

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

回答by codaddict

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

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

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

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

回答by Ming-Tang

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:

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

T t = p
p = q
q = t

where T is the type of p and q

其中 T 是 p 和 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;
}

回答by Sean Patrick Floyd

Sorting two ints

对两个整数进行排序

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

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

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.

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

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

顺便说一句:如果您的数据恰好是一个列表,则更好的交换方法是使用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

对 int[] 数组进行排序

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

显然,真正的目标是对整数数组进行排序。这是一个单行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;
}

回答by Bart

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

你必须内联。但是你真的不需要在 Java 中进行这种交换。

回答by Landei

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]);   
} 

回答by Lunivore

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 patternor dependency injection.

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

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.

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

回答by Andreas Dolk

Snippet-1

片段 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

片段 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;

回答by fastcodejava

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

Java 是按值传递的。所以swap你的意思是不可能的。但是您可以交换两个对象的内容,或者您​​可以内联进行。

回答by Tepken Vannkorn

//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;
        }
}