Quoc Danh Ngo
Quoc Danh Ngo

Reputation: 21

How to input the objects to a ArrayList <HashMap<String,Object>>

I have 1 object(Goods) have 2 attributes: String and boolean. How to input object Goods to ArrayList<HashMap<String, Object>> ? Because I want input ArrayList<HashMap<String, Object>> to SimpleAdapter

public class Goods {
    private String goodsName;
    private boolean isCheck = false;
    public String getGoodsName() {
        return goodsName;
    }
    public void setGoodsName(String goodsName) {
        this.goodsName = goodsName;
    }
    public boolean isCheck() {
        return isCheck;
    }
    public void setCheck(boolean isCheck) {
        this.isCheck = isCheck;
    }
}

Upvotes: 1

Views: 2391

Answers (2)

candied_orange
candied_orange

Reputation: 7344

package ngo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Goods g = new Goods();
        g.setGoodsName("foo");
        g.setCheck(true);

        Map<String, Goods> map = new HashMap<String, Goods>();
        map.put(g.getGoodsName(), g);

        List<Map<String, Goods>> list = new ArrayList<Map<String, Goods>>();
        list.add(map);

        System.out.println(list.get(0).get("foo").isCheck());
    }
}

Displays true

This should be an acceptable, if simple, structure for the data parameter of SimpleAdapter's constructor. A more exhaustive example of it's use can be found here

Upvotes: 1

simo.3792
simo.3792

Reputation: 2236

The following is the basic example, not runnable in itself.

ArrayList<HashMap<String, Goods>> listOfMappedGoods = new ArrayList<HashMap<String, Goods>>();

HashMap<String, Goods> goodsList = new HashMap<String, Goods>();

Goods g = new Goods();
g.setGoodsName("foo");
g.setCheck(true);

goodsList.add(g.getGoodsName(), g);
listOfMappedGoods.add(goodsList);

The point to note, is that just like every new Goods object needs to be created using new Goods(), each new goodsList needs to be created also using new HashMap<String, Goods>().

If you use something like goodsList.clear(), then you are still referring to the original map that was first added to the listOfMappedGoods, so you will clear that instead.

Upvotes: 0

Related Questions