有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java创建一个包含矩形和整数的数组

private Array<Rectangle> livinglamas;

我希望这个数组为每个矩形包含一个整数。这个整数应该在spawnLama()中指定,这样每个矩形都包含自己的值。我该怎么做

private void spawnLama() {
    Rectangle livinglama = new Rectangle();

    livinglama.x = MathUtils.random(-800, -400 - 64);
    livinglama.y = 0;
    livinglama.width = 64;
    livinglama.height = 64;

    livinglamas.add(livinglama);



    lastLamaTime = TimeUtils.nanoTime();
}

@Override
    public void render() {

    elapsedTime += Gdx.graphics.getDeltaTime();
    if(TimeUtils.nanoTime() - lastLamaTime > 1000000000L) spawnLama();


    Iterator<Rectangle> iter = livinglamas.iterator();
    while(iter.hasNext()) {
        Rectangle livinglama = iter.next();
        livinglama.x += LamaXBewegung * Gdx.graphics.getDeltaTime();
        if(livinglama.y + 64 < -575) iter.remove();
    }
   batch.begin();

    for(Rectangle livinglama: livinglamas) {
        batch.draw(animation.getKeyFrame(elapsedTime, true), livinglama.x, livinglama.y);
    }
    elapsedTime += Gdx.graphics.getDeltaTime();


共 (2) 个答案

  1. # 1 楼答案

    只需创建一些包装,将矩形和整数连接起来:

    public class DataHolder {
        public final Rectangle rect;
        public final int i;
    
        public DataHolder(Rectangle rect, int i) {
            this.rect = rect;
            this.i = i;
        }
    } 
    

    然后创建数据持有者的数组或arraylist:

    // array of dataholders (fixed size)
    DataHolder[] arr = new DataHolder[size];
    arr[0] = new DataHolder(someRectangle, someInteger);
    
    // arraylist of dataholders (dynamically expandable size) 
    ArrayList<DataHolder> arrlist = new ArrayList<>();
    arrlist.add(new DataHolder(someRectangle, someInteger));
    
  2. # 2 楼答案

    将其子类化,并使用子类而不是矩形:

    public class RectangleWithInt extends Rectangle {
        public int value;
    }
    

    或者使用Libgdx的ArrayMap。与Java的Map不同,您可以有重复的键,就像Array一样,它是按顺序排列的:

    private ArrayMap<Rectangle, Integer> livinglamas;
    
    //...
    
    livinglamas.put(livinglama, someInt);
    
    
    //...
    Iterator<Entry<Rectangle, Integer>> iter = livinglamas.iterator();
    while (iter.hasNext()){
        Entry<Rectangle, Integer> entry = iter.next();
        Rectangle lama = entry.key;
        int value = entry.value;
        //...
    }