gpt4 book ai didi

java - 将新元素添加到固定数组中

转载 作者:行者123 更新时间:2023-12-02 07:46:30 25 4
gpt4 key购买 nike

我在网上查了,但还是不明白,所以我在这里问这个问题。

在下面的小程序中,我创建了两个tour实例,我想做的就是将tour[2]放入而不更改“Tourtour[]=new Tour[2];”。

很多人推荐ArrayList,但我不知道在这段代码中该怎么做。

class Test{
public static void main(String args[]){

class Tour{
private String tourId;
private String tourDescription;
private double tourFee;
private int numOfBooking;

public Tour(String tourId,String tourDescription,double tourFee){
this.tourId=tourId;
this.tourDescription=tourDescription;
this.tourFee=tourFee;
}

public void print(){
System.out.println("ID:"+this.tourId);
System.out.println("Desc:"+this.tourDescription);
System.out.println("Fee:"+this.tourFee);
}
}


Tour tour[]=new Tour[2];
tour[0]=new Tour("AB001","TOUR1",100);
tour[1]=new Tour("AB002","TOUR2",200);
}
}

最佳答案

正如您所发现的,数组确实是固定长度的,因此我肯定会推荐 ArrayList。像这样使用它...

ArrayList<Tour> tours = new ArrayList<Tour>();
tours.add(new Tour("AB001","TOUR1",100));
tours.add(new Tour("AB002","TOUR2",200));

每次您想要添加新的游览时,只需再次调用 tours.add() 即可。

关于java - 将新元素添加到固定数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10764496/

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