Search code examples
javayamlbukkit

Weird stuff happening when moving objects from one YAML list to other


I have a problem regarding YAML files. When I try moving objects from one list to another inside of a .yml file and save it, weird stuff like this happens:

queued: &id001 []
current: *id001

What's supposed to happen:

current: Fraithor # <= Minecraft username, from queued, moved when running reQueue()
queued: [] # <= Or just nothing / delete list

reQueue() method:


        for (String path : FileBasics.FILETYPE.BANWAVE.getConfig().getStringList("queued")) {

            List<String> list = FileBasics.FILETYPE.BANWAVE.getConfig().getStringList("current");
            List<String> arrayList = new ArrayList<>();
            arrayList.add(path);

            list.addAll(arrayList);
            FileBasics.FILETYPE.BANWAVE.getConfig().set("current", list);
            list.remove(path);
            FileBasics.FILETYPE.BANWAVE.getConfig().set("queued", list);
            try {
                FileBasics.FILETYPE.BANWAVE.getConfig().save(FileBasics.FILETYPE.BANWAVE.getFile());
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

Obviously, I'm using a seperate class/emnum for the File saving (FileBasics). It's a pretty long code, so I pasted it on pastebin HERE (https://pastebin.com/XsqvYTBb)


Solution

  • You're pushing the same list to both current and queued. Java has reference semantics meaning that if you push arrayList to current, current holds a reference to arrayList so if you alter it, current will point to the altered list.

    Since you push the very same list to queued, YAML will add an anchor &id001 when the list first occurs, and an alias *id001 to refer to the same list afterwards.

    Since you don't want a list in current at all, it seems you want to do

    FileBasics.FILETYPE.BANWAVE.getConfig().set("current", path);
    

    Though I have no idea what kind of API this is and whether it accepts a string.