Save and load objects within a list

2

Hello, can anyone tell me why it is only loading the value, and the key is blank / null?

Code that I use to save and load:

        public static List<Pair<String, String>> cash_player = new ArrayList<>();
        public static void save() {
        File f = new File(plugin().getDataFolder(), "cash.dat");
        if (!(f.exists()))
            try {
                f.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
            oos.writeObject(cash_player);
            oos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("unchecked")
    public static void load() {
        File f = new File(Main.m.getDataFolder(), "cash.dat");
        if (f.exists()) {
            try {
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
                cash_player = (List<Pair<String, String>>) ois.readObject();
                ois.close();
            } catch (Exception e) {
                e.printStackTrace();

            }
        }
    }'

Class Pair :

class Pair<K, V> implements Serializable{
/**
 * 
 */
private static final long serialVersionUID = 6014244905733911500L;
K key;
  V value;

  public Pair(K key, V value) {
    this.key = key;
    this.value = value;
  }

}

How do I use to get key and value :

Cash.cash_player.get(0).value; // Retorna o valor salvo no objeto :D 
Cash.cash_player.get(0).key; // Retorna o nada =[

This is like you have not been saving completely.

    
asked by anonymous 07.11.2016 / 14:26

1 answer

4

Do this:

public static Map<String, String> cash_player = new HashMap<>();

public static synchronized void save() {
    File f = new File(plugin().getDataFolder(), "cash.dat");
    if (!(f.exists())) {
        try {
            f.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f))) {
        oos.writeObject(cash_player);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@SuppressWarnings("unchecked")
public static synchronized void load() {
    File f = new File(Main.m.getDataFolder(), "cash.dat");
    if (f.exists()) {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f))) {
            cash_player = (Map<String, String>) ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

And with that you can throw away your Pair class.

Also note the use of try-with-resources and synchronized .

    
07.11.2016 / 14:44