How to add values to variable of type hashmap without losing the previous values ?

1
0
-1

The next code is in the button action, the action is repetitive and my problem is that stored the value in this moment, the values previous are losing. returns only one value.

import java.util.HashMap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.io.Serializable;
import java.util.Random;
//int b = _documentIncrement;
Random  rnd = new Random();
String codigo = rnd.nextInt().toString();

//String nombre = field_File1.getFileName();
HashMap<String,String> listaDocs = new HashMap<String,String>();

//instanciar  clase
MiClase instancia = new MiClase();

//guardar en el hashmap
instancia.saveNameDocs(codigo,"nombre1",listaDocs);

//mostrar hashmap
instancia.showList(listaDocs);

public class MiClase implements Serializable {
        public static void saveNameDocs(String codigo, String nombre, HashMap <String,String> listaDocs){
                listaDocs.put(codigo, nombre);
        }
       
        public static HashMap <String,String> showList(HashMap <String,String> listaDocs){
                String clave;
                Iterator<String> item = listaDocs.keySet().iterator();
                while(item.hasNext()){
                        clave = item.next();
                        }
                return listaDocs;
        }
}
2 answers

1
+1
-1

Hi.

Random rnd = new Random();
String codigo = rnd.nextInt().toString();

This code always return the same value. When you had an entry in a hashmap with the same key, it replace the last value.

If you want a random key each time you click on the button, you need to create a process variable of type Random and call this variable in your script instead of creating a new one each time.

Comments

Submitted by stalinramirez on Thu, 05/07/2015 - 17:01

yes yannick, the random variable is a test, but the key is the commented variable "int b = _documentIncrement;" this is a process variable as you say and the result is similar. returns only one value. regards

1
0
-1

Hi,

it seem sthat listaDocs is reinitialized everytime "HashMap<String,String> listaDocs = new HashMap<String,String>();", how do you initialize the map?

Regards,

Notifications