2011-07-20 44 views
0

我试图覆盖已定义的变量。Java Array从属性加载

这里是我的代码:

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 

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

在此先感谢!

回答

2

问题是你正在存储传递给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中的类名,尤其是集合框架
  • 让您MyListstatic类:它并不需要从含有类Test访问任何领域 - 这是一个DTO
  • 从从设计的角度来看,你的代码突出了保持对可变对象引用的问题 - 你无法控制调用代码对你的对象(在这种情况下,作为数组)的作用。

避免此问题的一个简单的变化会是这样:

static MyList { 
    String[] words; 

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

语法String... words被称为“可变参数”的参数 - 它创建上只有该方法具有与参考飞阵列(尽管数组也可以传入,给你相同的问题)。 比较安全的方法是使阵列和存储的副本是,或提供一种方法,可以让你添加一个字(用列表来保存例如字)

  • 在一般,尽量避免阵列 - 更喜欢使用集合
+0

谢谢! 但是代码是如何垃圾?我试图学习正确的格式和所有。但不知道在哪里看! – Diesal11

+0

好吧,我会解释,因为你问 - 见编辑问题 – Bohemian

+0

对不起,在哪里?我看不到任何? – Diesal11

0

您需要在this.all中传递第二个元素的新数组。

String[] array = new String[2]; 

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

array = new String[2]; 

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

每次你把它传递到List构造时间变量array指向相同的内存。

0

您应该为第二个实例创建新的String [];通过重新使用第一个array,您只需更改all[0]all[1]都参考的同一阵列中的元素。换句话说,all[0]all[1]指的是内存中的相同位置。

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

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

或保存行的代码:

this.all[0] = new List(new String[] {"One", "Two"}); 
this.all[1] = new List(new String[] {"Two", "Three"}); 

而且这是一个不好的做法来命名类之一相同,常见的数据类型(java.util.List)。这将导致混乱。

+0

这是一个例子,所以没关系,但谢谢! – Diesal11