[英]How can I print out an arraylist and also How can I add errors checks to the arraylist?
我多年來一直試圖解決這個問題,但沒有運氣,我沒有進步。 有人可以幫我嗎。 我創建了一個arrayList,創建了一個getter類,並創建了一個方法。 我也可以向數組列表中添加內容,但是當我打印出arrayList時,它會打印出一些隨機文本。
下面是我創建的arrayList。
public static ArrayList<getArrayList> arrayList = new ArrayList<getArrayList>();
這是我的方法;
private static void addToArrayList(String a, double no1, int no2, int no3) {
try {
arrayList.add(new getArrayList(a, no1, no2, no3));
} catch (Exception e) {
e.printStackTrace();
}
}
這是我的吸氣類
public class getArrayList {
private String name;
private double seconds;
private int speed1;
private int speed2;
public String getName() {
return name;
}
public double getSeconds() {
return seconds;
}
public int getSpeed1() {
return speed1;
}
public int getSpeed2() {
return Speed2;
}
public StoreCommands(String storeName, double storeSeconds, int storeSpeed1, int storeSpeed2) throws Exception{
name = storeName;
seconds = storeSeconds;
speed1 = storeSpeed1;
speed2 = storeSpeed2;
}
}
在此列表上添加內容我使用我創建的方法
addToArrayList(String a, double no1, int no2, int no3) filled in with my values
並從arraylist接收東西,我用這個
for(getArrayList s : arrayList) {
System.out.println(arrayList + "\n")
;
如果我使用System.out.println(arrayList),它會打印出來,具體取決於我添加到arraylist的數量。
[StoreCommands@49a21b63]
除此之外,有人可以告訴我如何設置arrayList的大小,這樣,如果要添加的其他內容將不會添加並給出錯誤。 此外,一旦項目位於arrayList * 1st中,我還需要執行某些錯誤檢查。如果將一項添加到列表中,並且用戶在我想顯示錯誤之后嘗試再次添加相同的項目。(用戶可以添加相同的內容,但不能直接添加到剛添加的內容之后,則需要先添加其他內容。)* 2如果用戶要向列表中添加蘋果,我想將其限制為整個列表中只有2次,超過此數量的內容將不會添加,並且會顯示並顯示錯誤。
有人可以幫幫我,我將非常感激。
謝謝。
嘗試這個 -
for(getArrayList s : arrayList)
System.out.println(s + "\n");//This print the tostring of getArrayList class
再次重寫getArrayList
類的toString方法,以打印對象的實際字段值。 范例-
public class getArrayList {
public String toString(){
return name +"||" +seconds+"||"+ speed1+"||"+speed2;
}
}
注意:遵循Java命名標准,您的類名的后半部分將是大寫字母,並為該類提供一個相關的名稱。
您不必循環即可打印數組,只需執行以下操作:
System.out.println(Arrays.toString(arrayList.toArray()));
ArrayList
沒有限制大小的機制,如果要這樣做,則必須實現它。
例:
import java.util.ArrayList;
/**
* User: alfasin
* Date: 2/5/14
*/
public class RestrictedSizeArrayList<E> extends ArrayList<E> {
private static final int limit = 6;//example
@Override
public boolean add(E e){
if(this.size() > 5){
throw new IndexOutOfBoundsException("Can't add more than 5 elements to the ArrayList");
}
boolean result = super.add(e);
return result;
}
}
覆蓋toString方法將幫助您打印實際數據。 在您的class getArrayList
重寫它。 還有一件事是類名應以大寫字母開頭。
public String toString()
{
return "Name : "+name+" Seconds : "+seconds+" Speed1 : "+speed1+" Speed2 : "+speed2;
}
並像這樣使用
for(getArrayList s : arrayList)
System.out.println(s.toString);
您可以通過添加支票來限制大小
private static void addToArrayList(String a, double no1, int no2, int no3) {
try
{
if(arrayList.size < 10) //any size you want
arrayList.add(new getArrayList(a, no1, no2, no3));
else
System.out.println("ArrayList is full");
} catch (Exception e) {
e.printStackTrace();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.