java如何定义变量,如何定义无数个变量? * Java *

在创建游戏时,遇到需要大量矩形对象的问题。传统的声明方式(如car1, car2等)并不适用。解决方案是使用ArrayList来存储Rectangle对象,这样可以动态地增加或减少对象,而无需预定义无限数量的变量。通过ArrayList的get方法可以方便地访问特定位置的对象,并通过for循环检查矩形是否包含其他矩形。
摘要由CSDN通过智能技术生成

I am creating a game, and it requires an infinite number of Rectangles.

For example, let's say I name the variables car:

public Rectangle car1;

public Rectangle car2;

public Rectangle car3;

and so on,

Would there be an easier way? Like:

public int carNumber;

public Rectange car + carNumber;//if carNumber was one, it would be called car1

Also, I will need to test if the rectangles contain others.

解决方案

You can't and shouldn't try to declare an infinite number of anything -- just doesn't make sense. Instead use a collection such as an ArrayList that can hold a variable number of object references. e.g.,

private List carList = new ArrayList<>();

This won't work:

public Rectange car + carNumber;//if carNumber was one, it would be called car1

because variable names don't work that way, they can't be created by concatenating Strings. But don't worry about this, because the ArrayList will take care of this. The third item in the list would be obtainable easy enough: carList.get(2).

To see if any Rectangles in the list contain another Rectangle use a for loop and iterate through the collection:

for (Rectangle rect : carList) {

if (rect.contains(testRectangle) {

// this item contains the test Rectangle

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值