gpt4 book ai didi

java - 如果数组有效,如何创建传递的数组的深拷贝?

转载 作者:搜寻专家 更新时间:2023-10-31 19:44:10 25 4
gpt4 key购买 nike

因此,一个 IPv4 数组被传递给此方法,如果有效,则在实例变量“parts”中创建该数组的深拷贝

/**
* If the ip address from the array passed (data) is valid,
* makes a deep copy of the array passed in the instance variable parts.
* For example, if data = {192,168,0,1}, parts should become {192,168,0,1}
* by copying each item of data into corresponding item in parts.
* If the ip address passed is invalid (for example {500,4,60,216}
* or {192,16,01}, or {13,13,13,13,13}, parts should become {0,0,0,0}
*
* remember to reset the instance array parts before you do anything else
* @param data
*/
public void setParts(int[] data) {
this.parts = new int[4];
if (data.length != 4){
parts = new int[]{0,0,0,0};
}
else
for (int i = 0; i <= data.length; i++)
if ((data[i] < 0) || (data[i] > 255))
parts = new int[]{0,0,0,0};
else
parts[i] = data[i];
}

是我目前所拥有的。我可能会错过什么?

编辑:做了一个简单的改变:

for (int i = 0; i <= data.length; i++)

for (int i = 0; i < data.length; i++)

还有一个 JUnit 测试

    public void testSetPartsIntArray() {
correct1.setParts(new int[]{12, 14, 16, 18});
int[] a = correct1.getParts();
assertEquals(4, a.length);
assertEquals(12, a[0]);
assertEquals(14, a[1]);
assertEquals(16, a[2]);
assertEquals(18, a[3]);

correct1.setParts(new int[]{-12, 14, 16, 18});
a = correct1.getParts();
assertEquals(4, a.length);
assertEquals(0, a[0]);
assertEquals(0, a[1]);
assertEquals(0, a[2]);
assertEquals(0, a[3]);

工作直到

assertEquals(0, a[1]);

是什么导致它停在那里?

最佳答案

一旦发现无效值,就必须跳出循环:

for (int i = 0; i <= data.length; i++)
if ((data[i] < 0) || (data[i] > 255)) {
parts = new int[]{0,0,0,0};
break;
} else {
parts[i] = data[i];
}

在您失败的情况下,第一个元素 -12 无效,因此 parts 设置为 new int[]{0,0,0,0 },但随后您继续循环,由于其余数字有效,您最终得到 {0, 14, 16, 18} 而不是 {0 , 0, 0, 0}

关于java - 如果数组有效,如何创建传递的数组的深拷贝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39433325/

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