java - 我如何交换数组的数据?

标签 java arrays swap jcreator

   public class Swap_Numbers {

       public static void main(String[] args) {


              int numTens[] = {1, 2, 3, 4, 5}; // First array of numbers
              int numHundred[] = {100, 200, 300, 400, 500}; //Second Array of Numbers


       System.out.println (numTens[3]); // I want my numTens displays numHundred
       System.out.println (numHundred[4]); // I want my numHundred displays numTens
  }
 }

我只是不知道我应该使用什么代码来交换 numTens 和 numHundred 的数据而不使用额外的变量..希望有人能解释我如何做谢谢!

最佳答案

I just don't know what codes should i use to swap the data of numTens and numHundred without using extra variables

基本上,您不应该这样做。只需采用临时变量的简单路线:

int[] tmp = numTens;
numTens = numHundred;
numHundred = tmp;

对于整数,您可以实际上使用没有临时变量的算术交换数组中的值(这与交换变量引用的数组不同),但是如果真的发现自己处于想要这样做的境地,那将是非常奇怪的。示例代码:

import java.util.Arrays;

public class Test { 

    public static void main(String[] args) {
        int[] x = { 1, 2, 3, 4, 5 };
        int[] y = { 15, 60, 23, 10, 100 };

        swapValues(x, y);
        System.out.println("x: " + Arrays.toString(x));
        System.out.println("y: " + Arrays.toString(y));
    }

    static void swapValues(int[] a, int[] b) {
        // TODO: Validation
        for (int i = 0; i < a.length; i++) {
            a[i] += b[i];
            b[i] = a[i] - b[i];
            a[i] -= b[i];
        }
    }
}

即使在那里,我也会实际上使用一个临时变量来编写swapValues,但是上面的代码只是为了证明一个观点...

关于java - 我如何交换数组的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18912388/

相关文章:

java - Lucene 语法错误的查询字符串查询

php - 在 PHP 中从字符串创建无限深的多维数组

javascript - jQuery:仅打印数组中的一个结果

c++ - 如何使用 qi::hold[] 解析器指令。 (boost::swap 的属性类型问题)

list - 交换 Lisp 列表中的元素

java - ListIterator 交换当前和下一个

java - Apache Tomcat 7 显示空白页面 Mac OSX 10.8

java - 处理数据库或应用程序上的空值?

java - java中application.properties文件的问题

arrays - 在对组合数组进行排序时将已排序数组添加到重新分配的已排序数组的最佳方法