簡體   English   中英

將自定義arrayList的元素復制到字符串

[英]Copy elements of a custom arrayList to a String

我正在嘗試將自定義arrayList中的元素放到String中。 但是,當我嘗試對其進行迭代時,它僅顯示最后一個條目。 這適用於待辦事項應用程序,該應用程序應具有任務名稱,並根據任務是否完成而為1或0。

到目前為止,這是代碼:

Entry.java

public class Entry {
String S;
boolean b;
public Entry(String S, boolean b) {
    this.S = S;
    this.b = b;
}
public String getS() {
    return S;
}

public void setS(String S) {
    this.S = S;
}

public void setB(boolean b) {
    this.b = b;
}

public boolean isB() {
    return b;
}

}

MainActivity.java

ArrayList<Entry> mEntries;
String copy;
String name1;
int i;
public String getShareData() {

    for (Entry n : mEntries) {
        name1 = n.getS();
        i = boolToInt(n.isB());
        copy = name1 + "\t" + i + "\n";
    }
    return copy;
}

public int boolToInt(boolean b) {
    return b ? 1 : 0;
}

那是因為您要覆蓋每個條目的變量,而只保留最后一個元素。 我在您的代碼上添加的內容將在字符串副本的末尾附加每個條目。

ArrayList<Entry> mEntries;
String copy;
String name1;
int i;
public String getShareData() {
    copy = "";
    for (Entry n : mEntries) {
        name1 = n.getS();
        i = boolToInt(n.isB());
        copy += name1 + "\t" + i + "\n";
    }
    return copy;
}

public int boolToInt(boolean b) {
    return b ? 1 : 0;
}

您可以像下面這樣使用

public String getShareData() {
        copy="";
        for (Entry n : mEntries) {
            name1 = n.getS();
            i = boolToInt(n.isB());
            if(copy.length()==0)
                copy = name1 + "\t" + i + "\n";
            else
                copy = copy + name1 + "\t" + i + "\n";
        }
        return copy;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM