使用array.append方法将自己的对象类型添加到数组

时间:2013-04-14 02:59:40

标签: java arrays

private State USA = new State("United States of America");
private State CAN = new State("Canada");
private State MEX = new State("Mexico");
private State[] stateArray;
public static void main()
{
}


public void addState(State state) //I need a way to add the Private objects called State into an array here. The command must take User Interface
{
    stateArray = stateArray.add(state);
}

嗯,总而言之,我需要的是一些可以将项添加到数组中的方法,如addState数组中所示

2 个答案:

答案 0 :(得分:1)

使用List<State> sates = new ArrayList<State>();

public void addState(State state){
  sates.add(state);
}

答案 1 :(得分:0)

如果你想使用数组:

private State USA = new State("United States of America");
    private State CAN = new State("Canada");
    private State MEX = new State("Mexico");
    private State[] stateArray = new State[3];
    int index = 0;
    public static void main()
    {
    }


    public void addState(State state) //I need a way to add the Private objects called State into an array here. The command must take User Interface
    {
       if(index < stateArray.length)
           stateArray[index++] = state;
    }

或者您可以使用ArrayList代替数组。

private State USA = new State("United States of America");
    private State CAN = new State("Canada");
    private State MEX = new State("Mexico");
    private ArrayList<State> stateArray = new ArrayList<State>;
    public static void main()
    {
    }


    public void addState(State state) //I need a way to add the Private objects called State into an array here. The command must take User Interface
    {
        stateArray.add(state);
    }