gpt4 book ai didi

java - ArrayList#size() 的奇怪返回

转载 作者:行者123 更新时间:2023-12-01 16:51:26 25 4
gpt4 key购买 nike

我试图在HashMap中获取一个随机ArrayList,当我查看HashMap中的所有ArrayList时,大小为一切都应该是 2。

当我尝试将 Hashmap 中的 ArrayList 添加到另一个中时,就会出现问题。然后它返回大小为 0,即使 HashMap 中所有列表的大小都是 2。有人明白为什么吗?

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());

这是它在堆栈跟踪中返回的内容

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)

第 95 行是

int piece2 = rnd.nextInt(

如果HashMap中所有ArrayList的大小都是2,为什么points的大小却是0?

最佳答案

points == null替换为points.isEmpty()

points 变量不为 null,因为您在 while 循环之前为 points 变量分配了一个数组列表。我假设您想要做的是在点列表为空时进行检查。因此,进行建议的更改将解决您的问题。

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

ArrayList<Point> points = new ArrayList<>();
while(points == null) { // points is not null, it is just empty
// replace points == null with 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());

关于java - ArrayList#size() 的奇怪返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39399588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com