我有几种不同类型的ArrayLists。
每个存储从.csv文件中分割数据。
//NOTE: this is for understanding, syntax may not be correct.
ArrayList<String> name = {item1, item2, item3, item4};
ArrayList<String> type = {type1, type2, type3, type4};
ArrayList<Double> price = {price1, price2, price3, price4};
ArrayList<Integer> qty = {qty1, qty2, qty3, qty4};
在我的Item类中,我有一个像这样的构造函数,
public Items(String t, String n, Double p, Integer q){
type = t; //type mismatch : cannot convert from String to ArrayList<String>
name = n;//type mismatch : cannot convert from String to ArrayList<String>
price = p;//type mismatch : cannot convert from Double to ArrayList<Double>
qty = q;//type mismatch : cannot convert from Integer to ArrayList<Integer>
}
正如您所看到的,由于类型不同,我无法初始化构造函数。但是,在我的main方法中,我将每个变量调用为,
public static void main(String[] args){
ArrayList<Items> itm = new ArrayList<Items>();
Items general = new Items();
//place each item into object itm
for(int i = 0; general.name.size(); i++)
{
itm.add(new Items(general.type.get(i), general.name.get(i), general.price.get(i); general.qty.get(i)));
} //throws no syntax errors
如果我把“general.name.get(i)”作为例子,Java不会将其视为String而不是ArrayList吗?如何在构造函数中初始化这些变量?
编辑:当我使用general.type.get(i);我希望ArrayList类型中的索引在构造函数中等于t。对于n,p和q,这是相同的。
t = general.type.get(i);
答案 0 :(得分:1)
鸡蛋盒子......不是鸡蛋。
字符串列表...不是字符串。
含义:您无法直接从该单个字符串创建字符串列表。您只能将字符串添加到现有列表中。就像把鸡蛋放在鸡蛋盒里一样。
你需要:
type = new ArrayList<>();
type.add(t);
例如;或使用那个小助手方法更短:
type = Arrays.asList(t);
你的其他项目代码正在运行,因为general.type.get(i)
返回一个String对象;这正是你的Item构造函数所期望的 - 一个字符串对象。
答案 1 :(得分:0)
您正在尝试将ArrayList初始化为String。如果你告诉你真正想要实现的目标,我可以编辑代码来实现这一目标。
项目类
public class Item {
public static ArrayList<String> type_list = new ArrayList<>();
public static ArrayList<String> name_list = new ArrayList<>();
public static ArrayList<Double> price_list = new ArrayList<>();
public static ArrayList<Integer> qty_list = new ArrayList<>();
public String type;
public String name;
public Double price;
public Integer qty;
public Item (String type, String name, Double price, Integer qty){
this.type = type;
this.name = name;
this.price = price;
this.qty = qty;
}
}
主要类
public static void main(String args []){ ArrayList items_list = new ArrayList&lt;&gt;();
Item.type_list.add("type1");
Item.type_list.add("type2");
Item.type_list.add("type3");
Item.type_list.add("type4");
Item.name_list.add("name1");
Item.name_list.add("name2");
Item.name_list.add("name3");
Item.name_list.add("name4");
Item.price_list.add(price1);
Item.price_list.add(price2);
Item.price_list.add(price3);
Item.price_list.add(price4);
Item.qty_list.add(qty1);
Item.qty_list.add(qty2);
Item.qty_list.add(qty3);
Item.qty_list.add(qty4);
for(int i = 0; i < Item.type_list.size(); i++) {
System.out.println(.....);
}
}