如何在Java中编写基本交换函数

Mel*_*nda 53 java swap

我是java的新手.如何编写java相当于以下C代码.

void Swap(int *p, int *q)
{
   int temp;
   temp = *p;
   *p = *q;
   *q = temp;
} 
Run Code Online (Sandbox Code Playgroud)

Eng*_*uad 86

这是一招:

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 你会雇用一个会编写模糊代码的人吗?也许如果他们会解释为什么他们永远不会在生产代码中实际*做*. (7认同)
  • 加一表示技巧,减一表示如果没有一些很好的解释,它就不能在生产中广泛使用。它不能包含在单独的方法中,可以吗? (2认同)

Sea*_*oyd 40

排序两个整数

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

但是你可以做类似的事情:

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

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

顺便说一句:如果您的数据恰好是List,更好的交换方式是使用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. 
Run Code Online (Sandbox Code Playgroud)

对int []数组进行排序

显然,真正的目标是对一组int进行排序.这是一个单线Arrays.sort(int[]):

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

检查输出:

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

这里有一个简单的辅助函数来交换一组int中的两个位置:

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;
}
Run Code Online (Sandbox Code Playgroud)


Pra*_*shi 36

这是使用按位XOR(^)运算符在一行中交换两个变量的方法.

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);
   }
} 
Run Code Online (Sandbox Code Playgroud)

输出:

x和y的新值是10,5

  • 因为这不回答这个问题.问题是关于一个独立的函数,可以将两个变量作为参数并交换它们. (8认同)

Ole*_*lov 9

将此单线程用于任何原始数字类,包括doublefloat:

a += (b - (b = a));
Run Code Online (Sandbox Code Playgroud)

例如:

double a = 1.41;
double b = 0;
a += (b - (b = a));
System.out.println("a = " + a + ", b = " + b);
Run Code Online (Sandbox Code Playgroud)

输出是 a = 0.0, b = 1.41


Sjo*_*erd 5

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

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

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

  • @Lunivore:不,`Integer` 对象不是按值传递的。他们根本没有通过。**引用** *到 `Integer` 对象* 将按值传递。您只能在 Java 中传递引用和原始值,而不能传递对象! (4认同)
  • 整数无济于事,它们是不可变的。您需要一个容器,可以是 AtomicInteger(请参阅我的答案)或 1 元素列表或数组或任何此类内容 (2认同)