Java中可以写swap方法吗?

发布于 2024-08-03 02:44:34 字数 63 浏览 11 评论 0原文

问题是:编写一个交换两个变量的方法。这两个变量应该是原语。它不需要是通用的,例如两个 int 变量。有办法吗?!

Here is the question: write a method that swaps two variables. These two variables should be primitives. It doesn't need to be generic e.g. two int variables. Is there a way?!

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

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

发布评论

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

评论(13

木落 2024-08-10 02:44:34

虽然不可能编写一个简单地交换两个变量的函数,但可以编写一个辅助函数,它允许您:

  • 仅使用一个语句交换两个变量
  • <调用者代码中没有临时变量
  • 没有“装箱”基元
  • 有一些重载(其中一个使用泛型),它适用于任何类型

如何做到这一点:

int returnFirst(int x, int y) {
    return x;
}
<T> T returnFirst(T x, T y) {
    return x;
}
// other overloads as needed
int a = 8, b = 3;
a = returnFirst(b, b = a); // try reading this as a = b; b = a;
System.out.println("a: " + a + ", b: " + b); // prints a: 3, b: 8

这是有效的,因为 Java 语言保证(Java 语言规范,Java SE 7 版,第 15.12.4.2 节)所有参数都是从左到右计算的(与某些其他语言不同,其中计算顺序未定义) ),因此执行顺序为: 对

  1. b 的原始值进行求值,以便将其作为第一个参数传递给函数 对
  2. 表达式 b = a 进行求值,并且结果(b 的新值)作为第二个参数传递给函数
  3. 函数执行,返回 b 的原始值并忽略其新值
  4. 您分配结果到 a

如果 returnFirst 太长,您可以选择一个较短的名称以使代码更紧凑(例如 a = sw(b, b = a)< /代码>)。

假设您需要一个接一个地交换许多不同类型的变量。通过使用 returnFirst 就不需要 intAux、objAux 等。在某处错误使用错误变量的风险较小,因为没有额外的变量(至少在调用者中)。

While it is not possible to write a function that simply swaps two variables, it is possible to write a helper function that allows you to:

  • Swap two variables using only one statement
  • Without temporary variables in the caller's code
  • Without 'boxing' primitives
  • With a few overloads (one of them using generics), it works for any type

That's how you could do it:

int returnFirst(int x, int y) {
    return x;
}
<T> T returnFirst(T x, T y) {
    return x;
}
// other overloads as needed
int a = 8, b = 3;
a = returnFirst(b, b = a); // try reading this as a = b; b = a;
System.out.println("a: " + a + ", b: " + b); // prints a: 3, b: 8

This works because the Java language guarantees (Java Language Specification, Java SE 7 Edition, section 15.12.4.2) that all arguments are evaluated from left to right (unlike some other languages, where the order of evaluation is undefined), so the execution order is:

  1. The original value of b is evaluated in order to be passed as the first argument to the function
  2. The expression b = a is evaluated, and the result (the new value of b) is passed as the second argument to the function
  3. The function executes, returning the original value of b and ignoring its new value
  4. You assign the result to a

If returnFirst is too long, you can choose a shorter name to make code more compact (e.g. a = sw(b, b = a)).

Suppose you need to swap many variables of different types one after the other. By using returnFirst there's no need for intAux, objAux, etc. There's less risk of mistakenly using the wrong variable somewhere, because there are no extra variables (in the caller, at least).

画中仙 2024-08-10 02:44:34

如果不使用数组或对象,不,不可能在方法中执行此操作。

Without using an array or objects, no, it is not possible to do it within a method.

最佳男配角 2024-08-10 02:44:34

查看这篇 JavaWorld 文章,其中详细解释了它:

http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html

两个原语的交换永远不会起作用,因为原语在 Java 中是按值传递的。您甚至无法编写一个方法来交换两个对象。

就像@Thomas所说,你唯一能做的就是将你的原语包含在其他对象/数组中并修改它们。

Check out this JavaWorld article that explains it in detail:

http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html

A swap of two primitives will never work because primitives are passed by value in Java. You can't even write a method to swap two objects for that matter.

Like @Thomas said, the only thing you could do is have your primitives contained within other objects/arrays and modify those.

筱果果 2024-08-10 02:44:34

任何原始数的单行:

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

One-liner for any primitive numbers:

a += (b - (b = a));
巴黎盛开的樱花 2024-08-10 02:44:34

您可以创建 @marcus 的 swap 方法的通用版本,用于交换任意数量的相同类型的对象:

<T> T swap(T... args) {   // usage: z = swap(a, a=b, b=c, ... y=z);
    return args[0];
}

b = swap(a, a=b);
z = swap(x, x=y, y=z);

You can make a generic version of @marcus's swap method that swaps any number of objects of the same type:

<T> T swap(T... args) {   // usage: z = swap(a, a=b, b=c, ... y=z);
    return args[0];
}

b = swap(a, a=b);
z = swap(x, x=y, y=z);
左秋 2024-08-10 02:44:34

在java5中,我能想到的最接近的,可能对你有帮助的是:

AtomicInteger类(和其他类)有getAndSet()原子方法..

In java5, the closest I can think of, which may help you, is :

The AtomicInteger class (and others) have getAndSet() atomic methods ..

金兰素衣 2024-08-10 02:44:34

要编写交换原语的交换方法,您必须具有“输出”变量的概念,即其值被传递到调用上下文的变量。 C# 有这些,但您仍然必须指定它们是变量。

To write a swap method that swaps primitives you'd have to have the concept of "out" variables, i.e. variables whose values are passed up to the calling context. C# has those but you must still specify that they're out variables.

囍孤女 2024-08-10 02:44:34

该函数将交换两个整数

Integer[] swap(int a, int b){
    return new Integer[]{b,a};
}

This function will swap two ints

Integer[] swap(int a, int b){
    return new Integer[]{b,a};
}
一抹微笑 2024-08-10 02:44:34

这是一个交换两个原始变量的方法,

private void swap(){
    int a = 1;
    int b = 2;
    int temp = a;
    a = b;
    b = temp;
}

但它可能没有多大用处;)

好吧,说真的,如果变量是类级别的,就可以完成:

public class MyClass{
    // excuse horrible coding practice of public mutable fields
    public int a = 1;
    public int b = 2;

    public void swap(){
        int temp = a;
        a = b;
        b = temp;
    }
}

不过,我还是不明白它有什么用处

Here's a method that swaps two primitive variables

private void swap(){
    int a = 1;
    int b = 2;
    int temp = a;
    a = b;
    b = temp;
}

It might not be of much use though ;)

Ok seriously, it could be done if the variables are class level:

public class MyClass{
    // excuse horrible coding practice of public mutable fields
    public int a = 1;
    public int b = 2;

    public void swap(){
        int temp = a;
        a = b;
        b = temp;
    }
}

Again though, I fail to see what the use of this could be

转身以后 2024-08-10 02:44:34

我已经阅读了上面的答案,寻求解释为什么据说交换程序不能像用 C++ 编写的那样用 java 编写。
我做了以下方式
程序截图

I have read the above answers seeking an explanation as to why it is said that a swapping program cannot be written in java in the way it is written in c++.
I did the following way
program screenshot

黄昏下泛黄的笔记 2024-08-10 02:44:34

正如托马斯·欧文斯所说。您可能可以在 C 中通过 &reference 传递变量来做到这一点,但在 Java 中如果不使用对象就不行。

As Thomas Owens said. You could probably do it in C by passing variables by &reference, but afaik not in Java without using objects.

内心荒芜 2024-08-10 02:44:34

是的,可以使用一种方法交换两个变量。
但是你应该用空括号声明该方法,然后通过
参考(空括号)

这是一个示例,说明使用方法交换两个变量。

public class Swapping

{

static String A="Apple";
static String B="Bat";

    public static  void swap()
    {
       String k;
        k=A;
        A=B;
        B=k;

    }

  public static void main(String[] args) 
  {
    System.out.println("Before swapping");
    System.out.println("A= "+A);
    System.out.println("B= "+B);
    swap();
    System.out.println("After swapping");
    System.out.println("A= "+A);
    System.out.println("B= "+B);
  }

}

通过编译上述代码,输出如下:

Before swapping

A= Apple

B= Bat

After swapping

A= Bat

B= Apple

//In case of call by引用,如果我们在被调用方法

Yes it is possible to swap two variable using a method.
But you should declare that method with empty parentheses and then call it by
reference(empty parentheses)
.
Here is an example that illustrates swapping of two variable using a method.

public class Swapping

{

static String A="Apple";
static String B="Bat";

    public static  void swap()
    {
       String k;
        k=A;
        A=B;
        B=k;

    }

  public static void main(String[] args) 
  {
    System.out.println("Before swapping");
    System.out.println("A= "+A);
    System.out.println("B= "+B);
    swap();
    System.out.println("After swapping");
    System.out.println("A= "+A);
    System.out.println("B= "+B);
  }

}

By compiling the above code the output comes as follows:

Before swapping

A= Apple

B= Bat

After swapping

A= Bat

B= Apple

//In case of call by reference original value is changed if we made changes in the called method

时光暖心i 2024-08-10 02:44:34
public class Swap
{
    public static void main (String[]args)
    {
        int y = 5;
        int x = 4;
        int c;

        System.out.println("y = "+y);
        System.out.println("x = "+x);

        c=x; //c = 4
        x=y; //x = 5;
        y=c;

        System.out.println("\n");
        System.out.println("y= "+y);
        System.out.println("x= "+x);
    }    
}
public class Swap
{
    public static void main (String[]args)
    {
        int y = 5;
        int x = 4;
        int c;

        System.out.println("y = "+y);
        System.out.println("x = "+x);

        c=x; //c = 4
        x=y; //x = 5;
        y=c;

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