我正在为API设置值,我需要为类数据类型变量(它是一个数组)设置值,我需要知道如何设置值?
我在Java中尝试过,并且不断出现编译时错误
Items equipmenxxts = new Items ();
equipmenxxts.setDKU(savedRequest.DKUType());
equipmenxxts.setQuantity(savedRequest.getQuantity());
item.setEquipments(equipmenxxts);
**//error setEquipments(Items[]) in ItemOrder cannot be applied to (Items)**
public class ItemOrder implements java.io.Serializable {
private java.lang.String company,
private Items[] equipments; // class given below
public ItemOrder() {
}
public ItemOrder(Items[] equipments) {
this.equipments = equipments;
}
public java.lang.String getCompany() {
return company;
}
public void setCompany(java.lang.String company) {
this.company = company;
}
public Items[] getEquipments() {
return equipments;
}
public void setEquipments(Items[] equipments) {
this.equipments = equipments;
}
}
public class Items implements java.io.Serializable {
private java.lang.String DKU;
private int quantity;
public Items() {
}
public Items(String DKU, int quantity) {
this.DKU = DKU;
this.quantity = quantity;
}
}
@Service("clApiService")
public class NewApiImpl implements NewApiService {
@Override
public Request completeapiNewOrderRep(ServletWebRequest webRequest) {
try {
ItemOrder item = new ItemOrder();
item.setCompany(req.getCompany());
item.setEquipments(); //error setEquipments(Items[]) in ItemOrder cannot be applied to ()**
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
我希望仅将(req.setDKU和Quantity)的值设置为item.setEquipments();
答案 0 :(得分:0)
对于我研究的内容,为数组制作set
有点设计错误。但是,您可以制作一个void setItems(Items i)
,并在参数上引入ItemOrder
的某个索引,也可以制作一个“超集”,它不是真正的集合:
public void superSet(ItemOrder io){
this.equipments=io.setEquipments(Items[] i);
}
答案 1 :(得分:0)
.setEquipments(Items [])需要一组项目,但是您只传递了一个项目。
尝试首先创建一个包含项目的数组:
item.setEquipments(new Items[] {equipmenxxts});
或者您可以将equipmentxxts创建为数组:
final Items[] equipmenxxts = new Items[1];
equipmenxxts[0].setDKU(savedRequest.DKUType());
equipmenxxts[0].setQuantity(savedRequest.getQuantity());
item.setEquipments(equipmenxxts);
此外,以这种方式设置多个项目时,请确保您不公开类的内部状态,除非您真的知道自己在做什么,以及原因!您可以为您的方法考虑可变数量的参数:
public Items[] getEquipments() {
return Arrays.copyOf(equipments, equipments.length);
}
public void setEquipments(Items... equipments) {
this.equipments = Arrays.copyOf(equipments, equipments.length);
}
现在,您可以使用数组作为参数或自定义数量的项目调用.setEquipments(...):
item.setEquipments(e1, e2, e3);
您可以重新考虑变量的名称。我不明白为什么将ItemOrder对象称为“ item”-而您通过.setEquipments(...)
设置了“ Items”对象