gpt4 book ai didi

java - 为什么我的 Java 深度复制代码告诉我 "Assignment requires a deep, not shallow copy"?

转载 作者:行者123 更新时间:2023-12-01 13:49:04 24 4
gpt4 key购买 nike

我正在尝试提交这个声音处理程序,但我不断收到此错误:

Assignment requires a deep, not shallow copy. Are you just copying pointers, or copying the contents of the array?...

我想我正在对我的 public void set(double[] mySamples) 进行浅拷贝,但我是 Java 新手,真的不知道该怎么做。

public class Sound
{
private double[] temp;
private double[] samples;

public Sound() {
samples = null;
}

public Sound(Sound s) {
int j = 0;
double[] source = s.samples;
double temp[] = new double[source.length];
for(int i = 0; i < source.length; i++) {
temp[j] = source[i];
}
samples = temp;
}

public double[] get() {
return samples;
}

public void set(double[] mySamples) {
if (mySamples == null) {
throw new IllegalArgumentException("samples cannot be null");
} else {
samples = mySamples;
}
}


public void increaseVol(double percent) {
double [] result = new double[samples.length];
for (int i = 0; i < samples.length; i++) {
double reduce = samples[i] * percent;
result[i] = samples[i] + reduce;
}
samples = result;
}

public void wavSave(java.lang.String fileName) {
WavIO.write(fileName, samples);
}
}

最佳答案

我认为你需要做两处改变 -
1 你的构造函数正在对这些样本做一些奇怪的事情(并且可能会导致你的错误本身) - 我不确定你想要做什么,但我认为你应该推迟设置。

public Sound(Sound s) {
int j = 0;
set(s.samples);
}

2 只需复制 set 中的样本数组并存储即可。

public void set(double[] mySamples) {
if (mySamples == null) {
throw new IllegalArgumentException(
"samples cannot be null");
} else {
samples = new double[mySamples.length];
for (int i = 0; i < mySamples.length; i++) {
samples[i] = mySamples[i];
}
}
}

关于java - 为什么我的 Java 深度复制代码告诉我 "Assignment requires a deep, not shallow copy"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20110811/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com