![](/img/trans.png)
[英]How to get maximum value from of the first N values of an ArrayList?
[英]When copying the values from one Arraylist to another, all values get set as the last value entered in the first Arraylist
我在為自己編寫一個小程序時遇到問題。 我有一個可以從CSV讀取並將數據放入Farts類的arraylist的類(在您問之前,這是搏擊藝術的簡稱)。 這有效,當我測試輸出時,我可以看到從csv讀取的值。
AssetManager assetManager =context.getAssets();
ArrayList<Farts> arrayfarts = new ArrayList<Farts>();
InputStream csvStream = null;
System.out.println("right before try loop");
try {
csvStream = assetManager.open("farts.txt");
InputStreamReader csvStreamReader = new InputStreamReader(csvStream);
CSVReader csvreader = new CSVReader(csvStreamReader);
Farts fdata = new Farts();
String[] line;
int temp=0;
while ((line=csvreader.readNext())!=null){
System.out.println("inside of while");
fdata.fname=line[0];
fdata.description=line[1];
arrayfarts.add(temp,fdata);
System.out.println("Array iteration " + temp + " of " + arrayfarts.size());
System.out.println(arrayfarts.get(temp).fname + " " + arrayfarts.get(temp).description + "\n");
temp++;
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("ioexception"+e.toString());
}
return arrayfarts;
}
回到我的Main類中,然后使用.addall添加上面返回的內容。 但是,Arraylist中的數據僅由最后輸入的值填充。
arrayFarts.addAll(readcsv.retrieveFarts(this));
System.out.println(arrayFarts.get(0).fname + " " + arrayFarts.get(0).description + "\n");
int temp=0;
while (temp<arrayFarts.size()){
cupboard().withDatabase(db).put(arrayFarts.get(temp));
System.out.println("Array iteration " + temp + " of " + arrayFarts.size());
System.out.println(arrayFarts.get(temp).fname+" "+arrayFarts.get(temp).description+"\n");
temp++;
}
我想念什么嗎?
問題出在以下幾行:
fdata.fname=line[0]; fdata.description=line[1]; arrayfarts.add(temp,fdata);
您需要在每個循環中創建一個新的Farts實例,而不是更改單個實例。
instance multiple times to the list, while changing its values. 就目前而言,您只需將實例多次添加到列表中,同時更改其值。 這意味着您將在循環完成后僅看到最后解析的值。 您還將多次看到它,因為ArrayList
允許重復。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.