TheGamerPlayz TheGamerPlayz - 3 months ago 6
Java Question

Odd returning of ArrayList#size()

I am trying to get a random

ArrayList
in a
HashMap
, and when I look at all the ArrayLists in the
HashMap
the size of everything is 2 as it should.

The problem occurs when I try to add an
ArrayList
from the
Hashmap
into another. It then returns the size as 0 even though the size of all lists in the
HashMap
are 2. Does anyone see why?

for(Point p : defensePossibilities.keySet())
System.out.println(defensePossibilities.get(p).size());

ArrayList<Point> points = new ArrayList<>();
while(points == null) {
try {
int random = rnd.nextInt(defensePossibilities.size());
points.addAll(
defensePossibilities.get(random));
} catch(Exception e) {}
}
System.out.println("PointsSize: " + points.size());

int piece2 = rnd.nextInt(points.size());


This is what it returns in the stacktrace

2
2
2
2
2
2
2
2
PointsSize: 0
Exception in thread "Thread-0" java.lang.IllegalArgumentException: bound must be positive
at java.util.Random.nextInt(Unknown Source)
at me.xthegamerplayz.FirstGame.board.White_AI.move(White_AI.java:95)
at me.xthegamerplayz.FirstGame.board.ChessBoard.tick(ChessBoard.java:29)
at me.xthegamerplayz.FirstGame.board.ChessBoard.<init>(ChessBoard.java:21)
at me.xthegamerplayz.FirstGame.Game.render(Game.java:124)
at me.xthegamerplayz.FirstGame.Game.run(Game.java:70)
at java.lang.Thread.run(Unknown Source)


Line 95 is

int piece2 = rnd.nextInt(


Why is the size of
points
0 if all the ArrayLists in the
HashMap
are at the size of 2?

Answer

points not is null because you have instantiated it.
ArrayList<Point> points; this is null
So replace your code

for(Point p : defensePossibilities.keySet())
    System.out.println(defensePossibilities.get(p).size());

ArrayList<Point> points = new ArrayList<>();
while(points.isEmpty()) {
    try {
        int random = rnd.nextInt(defensePossibilities.size());
        points.addAll(
                defensePossibilities.get(random));
    } catch(Exception e) {}
}
System.out.println("PointsSize: " + points.size());

int piece2 = rnd.nextInt(points.size());

UPDATE
change

points.addAll(defensePossibilities.keySet());

2 UPDATE

public V get(Object key) Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

So

ArrayList<Point> a = new ArrayList<>();
a.addAll(defensePossibilities.keySet());
int random = rnd.nextInt(defensePossibilities.size());
points.add(a.get(random))