aionnetwork / AVM

Enabling Java code to run in a blockchain environment
https://theoan.com/
MIT License
49 stars 25 forks source link

Issue between AionMap and AionList #418

Closed ding-ma closed 3 years ago

ding-ma commented 3 years ago

In the following piece of code, I'm trying to map a 2d array into an AionMap by iterating through it.

        int[][] someints = new int[][]{
                {0},
                {1,2,3},
                {4,5},
                {},
                {6}
        };

        AionMap<Integer, AionList<Integer>> map = new AionMap<>();

        AionList<Integer> tmp = new AionList<>();
        int i = 0;
        for (int[] lst: someints){
            for (int e: lst){
                tmp.add(e);
            }
            map.put(i, tmp);
            tmp.clear();
            i++;
        }

Update: this implementation does not either. Creating a new object at every loop doesn't do the trick.

        int i = 0;
        for (int[] lst: someints){
        AionList<Integer> tmp = new AionList<>();
            for (int e: lst){
                tmp.add(e);
            }
            map.put(i, tmp);
            tmp.clear();
            i++;
        }

However, if you execute the code, the content of this AionMap is null. It is an issue between the AionList tmp, how it is cleared, and its reference within the AionMap.

The only way I found the fix the issue is by using a helper function as show bellow and setting each variable to an element of the map as show in the second code block.

    public AionList<Integer> parse2DArray(int index, int[][] array) {
        AionList<Integer> aionList = new AionList<>();
        for (int e : array[index]) {
            aionList.add(e);
        }
        return aionList;
    }
        int[][] someints = new int[][]{
                {0},
                {1,2,3},
                {4,5},
                {},
                {6}
        };

       AionList<Integer> e1 = parse2DArray(0, someints);
        earnedBadges.put(0, human);
        AionList<Integer> modern = parse2DArray(1, someints);
        earnedBadges.put(1, someints);
aion-shidokht commented 3 years ago

Hi, the problem is that you are using the same instance of AionList for all map values. So when you clear the content of tmp, all the references to it are also cleared. Instead of using the same tmp list and clearing it every time, try creating a new ArrayList inside your for loop and remove the clear method call.

ding-ma commented 3 years ago

Even with a new list inside it does not work. I have tried both. It would work in plain old java By putting a break point at the end of the loop and analyzing the content of that map image

image

aion-shidokht commented 3 years ago

That's because you are still clearing the list. There is no need for that.

ding-ma commented 3 years ago

Ah true. Thanks!