简体   繁体   English

将自定义arrayList的元素复制到字符串

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

I am trying to put the elements from my custom arrayList to a String. 我正在尝试将自定义arrayList中的元素放到String中。 But when i tried to iterate over it, it only prints the last entry. 但是,当我尝试对其进行迭代时,它仅显示最后一个条目。 This is for a todolist app that should have the name of the task and either 1 or 0 depending on whether the task is done or not. 这适用于待办事项应用程序,该应用程序应具有任务名称,并根据任务是否完成而为1或0。

This is the code so far: 到目前为止,这是代码:

Entry.java 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 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;
}

That's because you are overwriting your variable for each entry, only keeping the last element. 那是因为您要覆盖每个条目的变量,而只保留最后一个元素。 What I added on your code will append each entry at the end of the String copy. 我在您的代码上添加的内容将在字符串副本的末尾附加每个条目。

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;
}

You can use like below 您可以像下面这样使用

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