【问题标题】:how to swap Integer type in java [duplicate]如何在java中交换整数类型[重复]
【发布时间】:2015-08-21 23:17:16
【问题描述】:

如何在swap2() 函数中更改交换i,j 的值:

enter code here public class pass_by_ref {
        public static void swap(Integer i, Integer j)  //this will not change i j values in main 
        {
        Integer temp = new Integer(i);
        i = j;
        j = temp;
        }
        public static void swap2(Integer i, Integer j) 
        {
        i = 20;   //as i am setting i value to 20 why isn't it reflected in main and same for j
        j = 10;
        }
        public static void main (String[] args) throws java.lang.Exception
        {
        Integer i = new Integer(10);
        Integer j = new Integer(20);
        swap(i, j);
        System.out.println("i = " + i + ", j = " + j);
        swap2(i, j);
        System.out.println("i = " + i + ", j = " + j);
        }
        }

输出:

        i=10,j=20
        i=10,j=20;

我认为 Integer i=new Integer(10) 创建了一个值为 10 的对象 i,所以当我在 swap2() 中写入 i=20;j=10 时,我正在设置值!..为什么它不起作用 我知道swap() 不会改变i,j 的值,但为什么swap2() 不起作用? 那么在swap2() 中进行什么更改以便交换值。

【问题讨论】:

  • 你不能。 Java 是按值传递的。编写一个方法来做到这一点是不可能的。
  • 我可以用 2 个整数 i 和 j 创建一个类,然后创建该类的一个对象,然后交换值吗?
  • 是的,您可以这样做,或者您可以使用答案中的数组。它之所以有效,是因为数组是可变的。
  • 我曾经为这样的问题写了一个可变包装类,如果你不想使用返回数组(无论出于什么原因)你可以使用这个肮脏的技巧。

标签: java pass-by-reference pass-by-value


【解决方案1】:

Java总是按值传递,Integer 是不可变的,您无法更新调用者引用。您可以使用数组(数组中存储的值是可变的)。因为数组是Object,所以它的值是通过对数组实例的引用的值传递的,因此您可以修改数组中的值。有点像,

static void swap(int[] arr, int i, int j) {
    // error checking
    if (arr == null || i == j) {
        return;
    }
    if (i < 0 || j < 0 || i > arr.length - 1 || j > arr.length - 1) {
        return;
    }
    // looks good, swap the values
    int t = arr[i];
    arr[i] = arr[j];
    arr[j] = t;
}

然后你可以这样称呼它

public static void main(String[] args) {
    int[] arr = { 10, 20 };
    System.out.println(Arrays.toString(arr));
    swap(arr, 0, 1);
    System.out.println(Arrays.toString(arr));
}

然后(在输出中)值交换

[10, 20]
[20, 10]

【讨论】:

  • 好的,谢谢...但是“Integer i=new Integer(10)”是创建对象还是就像原始数据类型一样?
  • @rashik Integer 是 Java 中的不可变包装类型。另外,我相信有一个实例池正在使用来保证Integer(10) == 10。
  • 在不使用第三个变量的情况下交换 2 个整数的“有趣”技巧:a=a+b;b=a-b;a=a-b;
猜你喜欢
  • 2012-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-12
  • 2013-04-07
  • 1970-01-01
  • 2015-06-01
  • 2017-11-05
相关资源
最近更新 更多