gpt4 book ai didi

java - 如何在 Java 中将新的 Listing 对象添加到数组的下一个索引处?

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

public class DataStructure{ 

private Listing[] data; // an array of listing objects

private int size = 100;

private int next = 0;


DataStructure(){

// allocate the array to 100 elements

data = new Listing[100];
}


DataStructure(int numberofListings){

this.numberofListings= numberofListings;

}


public void addListing(Listing newListing){

// how would I add a new Listing object to the array at index next

}

public void showAllListing(){

// this method will output the values of the data members of all Listing objects

}


public static void main(String[] args){

DataStructure obj1= new DataStructure();

Listing l1= new Listing();




}






}
for(i=0; i<100; i++) { 
data[index];
}

大家好,

我试图弄清楚如何在 Java 程序中的下一个索引处将新的 Listing 对象添加到数组中。我是否必须使用 for 循环并在该 for 循环内部,我是否必须手动将新元素设置为名为 next 的索引到数组中的特定位置?我知道我需要做一些类似上面的伪代码示例的事情。另外,为了测试该新元素和所有其他元素都在数组内,我需要调用 showAll 方法,对吧?有人能帮我吗?谢谢!

最佳答案

我建议您使用如下所示的内容:

  • 使用构造函数设置大小,不需要保存在变量中( data.length 会给你)
  • 添加元素时,将其添加到前一个元素的旁边,然后将元素数量增加 1
<小时/>
public class DataStructure {

private Listing[] data;

private int next = 0;

DataStructure(int numberofListings) {
data = new Listing[numberofListings];
next = 0;
}


public void addListing(Listing newListing) {
if (next < data.length) {
data[next] = newListing;
next++;
}else{ // facultative
System.out.println("Invalid operation -> array is full"); // it is
} // juste informative
}

public void showAllListing() {
for (int i = 0; i < next; i++) { //print only not empty boxes, stop to 'next'
System.out.println(data[i]);
}
}

public static void main(String[] args) {
DataStructure obj1 = new DataStructure(100);

Listing l1 = new Listing();
obj1.addListing(l1); //next = 0; set item to 0 positon, then next = 1
obj1.addListing(new Listing()); //next = 1; set item to 1 positon, then next = 2

obj1.showAllListing();
}
}
<小时/>

改进:

  • 当您更熟悉 Java 时,您可以看看 List<>允许动态大小

关于java - 如何在 Java 中将新的 Listing 对象添加到数组的下一个索引处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46308210/

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