如何使两个具有不同引用的数组? [英] How to make two arrays having different references?

查看:49
本文介绍了如何使两个具有不同引用的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须反转两个数组,以便它们都具有相同的值但引用不同.

I have to reverse two arrays so that, they both have the same values but different references.

到目前为止,这是我的代码.

Here is my code so far.

但是当两个数组都指向相同的程序参数时如何实现呢?

But how to achieve that when both arrays are pointing to the same program arguments?

为什么 String [] 引用会反转 String [] 值而不是反转程序参数?

And why does String[] reference reverse the String[] values instead of reversing the program arguments?

例如.如果程序参数是 1 2 3 4 5 :

For example. If the program arguments were 1 2 3 4 5:

String[] values = 5 4 3 2 1
String[] reference = 1 2 3 4 5

public static void main(String[] args) {
    String[] values = changeValues(args);
    System.out.println(Arrays.toString(values));
    String[] reference = changeReference(args);
    System.out.println(Arrays.toString(reference));

    if (!testSameValues(values, reference)) {
        System.out.println("Error: Values do not match !");
    }

    if (testSameReference(values, reference)) {
        System.out.println("Error: References are the same !");
    }
}

public static String[] changeValues(String[] x) {
    for (int i = 0; i < x.length / 2; i++) {
        String temp = x[i];
        x[i] = x[(x.length - 1) - i];
        x[(x.length - 1) - i] = temp;
    }
    return x;
}

public static String[] changeReference(String[] y) {
    for (int i = 0; i < y.length / 2; i++) {
        String temp = y[i];
        y[i] = y[(y.length - 1) - i];
        y[(y.length - 1) - i] = temp;
    }
    return y;
}

public static boolean testSameValues(String[] x, String[] y) {
    if (x.equals(y)) {
        return true;
    } else
        return false;
}

public static boolean testSameReference(String[] x, String[] y) {
    if (x == y) {
        return true;
    } else
        return false;
}

推荐答案

changeReference和changeValues方法具有相同的作用-反转数组.这就是为什么最终您看到相同的输入数组的原因.

changeReference and changeValues methods do the same thing - reverse the array. That is why in the end you see the same input array.

要更改引用,您需要创建一个新数组,并使用与原始数组相同的元素填充它.

To change the reference, you need to create a new array and populate it with the same elements from the original one.

将数组复制到一个新数组中

copying array into a new one

public static String[] changeReference(String[] y) {
    String[] copy = new String[y.length];
    for(int i = 0; i < y.length; i++) {
        copy[i] = y[i]
    }
    return copy;
}

这篇关于如何使两个具有不同引用的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆