gpt4 book ai didi

Java 数组从属性加载

转载 作者:行者123 更新时间:2023-12-02 08:14:13 25 4
gpt4 key购买 nike

我正在尝试覆盖已定义的变量。

这是我的代码:

package com.diesal11;

import java.lang.reflect.Array;

public class Test{

private class List {
public String[] words;

public List(String[] array) {
this.words = array;
}
}

public List[] all;

public Test() {
this.all = new List[2];
String[] array = new String[2];

array[0] = "One";
array[1] = "Two";
this.all[0] = new List(array);

array[0] = "Three";
array[1] = "Four";
this.all[1] = new List(array);

System.out.println(this.all[0].words[0]);
System.out.println(this.all[0].words[1]);
System.out.println(this.all[1].words[0]);
System.out.println(this.all[1].words[1]);
}

public static void main(String[] args) {
Test test = new Test();
}

}

问题是控制台打印出来:

Three
Four
Three
Four

我该如何解决这个问题?我需要这个的实际代码是以这种方式设置的,所以它不能改变太多。

提前致谢!

最佳答案

问题是您正在存储对传递给 List 构造函数的数组的引用。
然后,您更改同一数组并将其传递给第二个 List 对象。

相反,创建一个数组并像这样传递它:

...
String[] array = new String[2];

array[0] = "One";
array[1] = "Two";
this.all[0] = new List(array);

array = new String[2]; // CREATE A NEW ARRAY
array[0] = "Three";
array[1] = "Four";
this.all[1] = new List(array);
...

已编辑 - 添加了与样式相关的反馈

您的更大问题是这段代码有很多样式问题:

  • 不要调用类 List:您应该避免使用 JDK 中的类名称,尤其是来自 Collections 框架的类名称
  • 使您的 MyList静态:它不需要访问包含类 Test 中的任何字段 - 它是 DTO
  • 从设计的角度来看,您的代码突出了保留对可变对象的引用的问题 - 您无法控制调用代码对您的对象(在本例中为数组)执行的操作。

避免此问题的简单更改如下:

static MyList {
String[] words;

public MyList(String... words) {
this.words = words;
}
}
...
this.all[0] = new List("one", "two");

语法 String...words 被称为“varargs”参数 - 它动态创建一个只有该方法有引用的数组(尽管也可以传入数组,给出你也有同样的问题)。唯一安全的方法是创建数组的副本并存储它,或者提供一种允许您添加单词的方法(使用列表来保存单词)示例)

  • 一般来说,尽量避免使用数组 - 更喜欢使用集合

关于Java 数组从属性加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6756502/

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