我将如何定义无数个变量? * Java * [英] How would I define an infinite number of variables? *Java*

查看:313
本文介绍了我将如何定义无数个变量? * Java *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个游戏,它需要无限数量的矩形. 例如,假设我将变量命名为car:

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;

以此类推,

会有更简单的方法吗?喜欢:

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. <-- I know how to do this.

推荐答案

您不能也不应该尝试声明无限数量的任何内容-只是没有意义.而是使用诸如ArrayList之类的集合,该集合可以容纳可变数量的对象引用.例如,

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<Rectangle> carList = new ArrayList<>();

这行不通:

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

因为变量名不能那样工作,所以不能通过串联字符串来创建它们.但是不必担心,因为ArrayList会解决这个问题.列表中的第三项很容易获得:carList.get(2).

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).

要查看列表中是否有任何矩形包含另一个矩形,请使用for循环并遍历集合:

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
  }
}

这篇关于我将如何定义无数个变量? * Java *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆