Problem with List and Hashmap

Asked

Viewed 105 times

1

I have a list as stated below:

List<Map<String, String>> lista = new ArrayList<Map<String, String>>();

Map as declared below:

Map<String, String> mapa = new HashMap<String, String>();

Values are loaded in a for with results of a web service as below:

if (propInfo1.getName().toString().equals("competencia")) {
    SoapObject obj2 = (SoapObject) obj1.getProperty(ret1);
    for (int ret2 = 0; ret2 < obj2.getPropertyCount(); ret2++) {
        PropertyInfo propInfo2 = new PropertyInfo();
        obj2.getPropertyInfo(ret2, propInfo2);
        competencia = new Competencia();
        if (propInfo2.getName().toString().equals("codCal")) {
            mapa.put("codcal", obj2.getProperty(ret2).toString());
        }
        if (propInfo2.getName().toString().equals("perRef")) {
            Object objData = (Object) obj2.getProperty(ret2).toString();
            try {
                Date date = DataUtils.stringToDate(objData.toString());
                mapa.put("perref", DataUtils.dataMesAno(date));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (propInfo2.getName().toString().equals("tipCal")) {
            mapa.put("tipcal", obj2.getProperty(ret2).toString());
        }
    }
    Log.i("Valor do Mapa", mapa.toString());
    lista.add(mapa);
    Log.i("Valor da Lista", lista.toString());
}

But the values are being loaded duplicated

18704-18704/br.com.fjsa16.holerite I/Valor do Mapa﹕ {tipcal=Cálculo Mensal, perref=Abril / 2015, codcal=405}
18704-18704/br.com.fjsa16.holerite I/Valor da Lista﹕ [{tipcal=Cálculo Mensal, perref=Abril / 2015, codcal=405}]
18704-18704/br.com.fjsa16.holerite I/Valor do Mapa﹕ {tipcal=Cálculo Mensal, perref=Março / 2015, codcal=401}
18704-18704/br.com.fjsa16.holerite I/Valor da Lista﹕ [{tipcal=Cálculo Mensal, perref=Março / 2015, codcal=401}, {tipcal=Cálculo Mensal, perref=Março / 2015, codcal=401}]

In logcat the map is loaded correctly but when adding in the list it is loaded in duplicate, that is to say the values are the same.

Has anyone ever come across this? Can you help me?

  • I suspect that you are initializing the map object in a wrong place, can edit your question and put more code?

  • Otávio, it was just this... I didn’t notice! Thank you. Hug.

  • 1

    @Octavian can add an answer with an explanation of the problem?

  • 2

    @Sergio actually gets complicated because I just gave a suggestion totally "in the dark". Stroke of luck, hehehe. I think it’s fair the ADP (@Fábioazevedo) put an answer himself. :)

  • @Fabio Azevedo, could put the solution, in case someone has the same problem?

  • Guys, I just declared the Hashmap below in if... if (propInfo1.getName().toString().equals("competencia")) { Map<String, String> map = new Hashmap<String, String>();

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.