【问题标题】:Create a Java class With a variable(arrayList) of the same class使用同一类的变量(arrayList)创建一个Java类
【发布时间】:2012-01-20 15:55:01
【问题描述】:

您好,我想创建一个包含具有相同类的数组的类。

我尝试使用下面指定的代码,但我创建的数组是无限的。

public class State {

private String Valor1;
private String Valor2;
private ArrayList arrayStatesAnteriores;

}

我做了设置并通过 netbeans 的重构得到了结果

state.setArrayStatesAnteriores(arrayStateAnteriores);

但我有数组无限的问题。有什么想法吗?

【问题讨论】:

  • 但我有问题数组是无限的有什么想法吗?请展开
  • 我们需要更多信息来提供帮助。
  • 所以基本上你想要一个可以是任意大小的状态列表?
  • 听起来他的构造函数创建了同一个类的实例,因此是递归的,触发堆栈溢出。

标签: java class arraylist


【解决方案1】:

我的理解是这样的:你有一个代表程序在给定时刻的状态的类,并且你想保留一个程序状态的列表,这就是为什么你说这是一个无限的列表。

首先是 State 类,它有两个字段 value1value2 一个构造函数,它将这两个字段设置为传递的值:

public class State {

    /**
     * This is the constructor 
    */
    public State(String value1, String value2){
        this.value1 = value1;
        this.value2 = value2;
    }

    // Omiting getters/setters for brevety.
    // This will be set by the constructor using the values that it
    // receives as arguments 
    // e.g
    // new State("My Val1","My Val2");
    private String value1;
    private String value2;
}

那么这个类将包含在States的数组中

List<State> states =  new ArrayList<States>();

然后你会在你的主类或其他类中使用这些类:

import State;
public class Program {

    // This array holds the states that the program has had.
    private static List<State> states =  new ArrayList<State>();
    public static void main(String[] args){
        // ...
        // Do something
        // ...

        // Save the states
        states.add(new State("State 1","Value 1"))
        // Save another state
        states.add(new State("State 2","Value 2"))
        // The arraylist  now contains two states of the program.
    }

}

希望您可以随时提出更多问题。

【讨论】:

  • 对不起,我不太了解java,我也不清楚当我的班级有像这样的变量时 public class State { private String value1;私有字符串值2; List states = new ArrayList();公共状态(字符串值1,字符串值2){ this.value1 = value1; this.value2 = value2;} }
【解决方案2】:

使用List,并初始化它:

public class State {
  private List<State> statesAnteriores = new ArrayList<State>();
}

【讨论】:

  • 你不能实例化List,你是说ArrayList吗?
【解决方案3】:

首先,您的代码只需几周时间:

原来如此

public class State {

    private String Valor1;
    private String Valor2;
    private List<State> arrayStatesAnteriores;



}

关于您的问题,“数组是无限的”是什么意思? 你的意思是你设置后是null

state.setArrayStatesAnteriores(arrayStateAnteriores);

原因可能是你自己设置了列表的值,它是空的。

试试这样的:

state.setArrayStatesAnteriores(new ArrayList<State>());

【讨论】:

  • 当我调试代码时,我有类似的东西:状态:araryState state...arrayState....array...ArrayState。我将尝试使用列表:D 谢谢
  • 当我调试代码就像 State -Value 1 -Array States[0]State -Value 1 -Array States[0]]State -Value 1 -Array States[0] States[1] States[2] States[1]State -Value 1 -Array States[0] States[1] States[2] States[2]State -Value 1 -Array States[0] States[1] States[2] States[ 1]State -Value 1 -Array States[0] States[1] States[2]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多