我想添加一個新的對象到ArrayList。每個項目的對象將有3個屬性:如何將新對象添加到ArrayList?
- itemNum
- 資訊
- 成本
我也有3類:
- 項目類定義存儲在單個項目目錄。
- 目錄類維護着Item對象的列表。
- 客戶類別w/main方法。
我有集合並獲取在Item類中,我在Catalog中有ArrayList。在客戶端中,我可以選擇添加,刪除或編輯對象。如何正確添加一個新的Item對象到ArrayList?
我得到Item類編譯好,但目錄和客戶端類不編譯。這是我與目錄類得到的錯誤:
Catalog.java:35: error: no suitable method found for add(int,String,double)listOfObjects.add(newItemId, newDescription, newCost);
method ArrayList.add(int,Item) is not applicable
(actual and formal argument lists differ in length)
method ArrayList.add(Item) is not applicable
(actual and formal argument lists differ in length)
下面是項目類
Public class Item
{
private int itemNum;
private String info;
private double cost;
public Item()
{ //start constructor
itemNum = 0; //default values
info = "x";
cost = 0;
} //end constructor
public CatalogItem(int newItemNum, String newInfo, double newCost)
{ //start overload constructor
this.itemNum = newItemNum;
this.info = newInfo;
this.cost = newCost;
} //end overload constructor
下面
是一組代碼itemNum
/獲取 public int getItemNum()
{ //start itemNum accessor
return itemNum;
} //end getItemNum
public void setItemNum(int newItemNum)
{ //start itemNum mutator
this.itemNum = newItemNum;
} //end setItemNum
} //end Item class
//下面是我的產品目錄類
import java.util.*;
public class Catalog
{ //start class
private ArrayList<CatalogItem> listOfObjects = new ArrayList<CatalogItem>(100); //creates ArrayList
Item newItem = new Item(newItemNum, newInfo, newCost); //instantiates Item class
/*
public Catalog()
{ //start constructor
} //end constructor
*/
public void add(CatalogItem newItem) //method adds a new Item object to the array list
{ //start add
listOfObjects.add(newItem);
} //end add
public void add(int itemNum, String info, double cost) //accepts parameters from main method to add to new object
{ //start add
int newItemNum = itemNum;
String newInfo = info;
double newCost = cost;
newItem.setItemNum(newItemNum);
newItem.setInfo(newInfo);
newItem.setCost(newCost);
listOfObjects.add(newItemNum, newInfo, newCost);
} //end add
} //end class
belo w是客戶端類。它接收來自用戶關於itemNum,info和成本的輸入
import java.util.*; //allows use of Scanner class
public class Client
{ //start client class
public static void main(String[] args)
{ //start main
Catalog serv = new Catalog(); //creates instance of Catalog class
Scanner scan = new Scanner(System.in); //creates instance of Scanner class called scan
public void add(int itemNum, String info, double cost) //accepts parameters from main method to add to new object
{ //start add
int newItemNum = itemNum;
String newInfo = info;
double newCost = cost;
newItem.setItemNum(newItemNum);
newItem.setInfo(newInfo);
newItem.setCost(newCost);
listOfObjects.add(newItemNum, newInfo, newCost); //adds the object to the ArrayList
} //end add
}
任何幫助將不勝感激。
您正在使用的構造'新項目(newItemNum,newInfo,newCost)創建項目;'但是我可以」沒有看到它。 – omainegra