-2

I would like to assign the string-type data in my list to an object in a class. I tried for loop, but I couldn't create it, I can't do it directly. How can I solve this problem?

CheckModel.class

public class CheckModel {
    private String name;
    private boolean isSelected;

    public CheckModel(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isSelected() {
        return isSelected;
    }

    public void setSelected(boolean selected) {
        isSelected = selected;
    }}

xFragment.java class

ArrayList list2 = new ArrayList();

..
for loop
list2.add("...");
..

getCheckModel(list2);


private CheckModel[] getCheckModel(ArrayList<String> list)
    {

//How do I make the assignment here?

        return checkModels;
    }
  • `ArrayList list2 = new ArrayList();` **Warning:** you're using raw types. Never do that, always provide type arguments. – MC Emperor Mar 29 '19 at 11:57

2 Answers2

1

Perhaps you want this

private CheckModel[] getCheckModel(ArrayList<CheckModel> list)
{
    return list.toArray(new CheckModel[list.size()]);
}

Edit

First create an ArrayList<CheckModel> as :

private ArrayList<CheckModel> mList = new ArrayList<>();

Then do a for loop to create items on that list :

for(int i = 0; i<=10; i++){
  mList.add(new CheckModel("Name "+i,(i%2==0 ? true : false));
}

Or if you want add them manually :

mList.add(new CheckModel("Example 1", true);
mList.add(new CheckModel("Example 2", false);

Then change your method to :

private CheckModel[] getCheckModel(ArrayList<CheckModel> list)
{
  return list.toArray(new CheckModel[list.size()]);
}
Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148
0

Basically same idea as other answers but why not add to the CheckModel class since it is a form of construction:

public static CheckModel[] getAll (ArrayList<String> list) {
    ArrayList<CheckModel> result = new ArrayList<CheckModel>();
    for (String s : list) {
        // assume isSelected is false
        result.add(new CheckModel(s));
    }
    return result.toArray(new CheckModel[0]);
}