本文介绍了如何复制串的二维阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与使用字符串的二维数组的程序工作(可能不是明智的开始,但EH),我想要写一个函数,这些阵列(一个假设数组1 ),使一个独立的副本,并将其返回(假设数组2)。然而,当我再更改数组2的值,它似乎在数组1中得到体现。

I'm working with a program that uses two-dimensional arrays of Strings (probably not that smart to begin with, but eh), and I'd like to write a function that takes one of these arrays (let's say array1), makes an independent copy, and returns it (let's say array2). However, when I then change a value in array2, it seems to be reflected in array1.

我目前的功能看起来是这样的:

My function currently looks something like this:

public static String[][] copy(String[][] matrix, int n) {
    String[][] out = new String[n+1][n+1];
    for (int i = 0; i < n+1; i++)
        for (int j = 0; j < n+1; j++) {
            if(matrix[i][j] != null) {
                String cp = new String(matrix[i][j]);
                out[i][j] = cp;
            }

        }

    return out;
}

我宣布一个新的字符串数组,然后通过它遍历单独复制每个值。如果没有工作,我甚至试过明确声明从每个旧字符串新的字符串,并把数组中来代替。

I declare a new array of Strings, and then iterate through it, copying each value individually. When that didn't work, I even tried explicitly declaring a new string from each old string and putting that in the array instead.

谁能告诉我,我要去哪里错了?

Can anyone tell me where I'm going wrong?

推荐答案

您方法看起来像它应该工作,虽然在正作为参数传递使其脆,使用输入数组的长度字段会更好,你甚至可以处理不规则数组的方式。

Your method looks like it should work, though passing in n as a parameter makes it brittle, using the input array's length field would be better, and you could even handle jagged arrays that way.

制作内容的拷贝是没有必要的,因为字符串不能被改变 - 这导致的主要问题:你在做什么样的变化,似乎在副本中得到体现?向我们展示code,它这样做了。

Making a copy of the contents is not necessary, since Strings cannot be changed - which leads to the main question: What kind of changes are you making that seem to be reflected in the copy? Show us the code that does this.

这篇关于如何复制串的二维阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 08:26