在ArrayList Java中获取相同的输出

时间:2014-09-08 08:36:43

标签: java oop arraylist

所以我正在创建一个java类" Tile",并且我添加了一个ArrayList,因此我可以将这些tile存储在其中。 我想循环遍历数组并打印出每个图块的细节。我得到了同样的结果 每次输出。这是主要的课程:

package com.OriginsB;

import java.util.ArrayList;

public class Main {
     private static final int range = 5;
     public static ArrayList<Tile> tilearr = new ArrayList<Tile>(range);
     public static void main(String[] args) {
          for(int i=1; i<range; i++){
               tilearr.add(new Tile(i, i+1));
          }
          for(int i=0; i<tilearr.size(); i++){
              System.out.println(tilearr.get(i));
          }
     }
}

这是Tile课程:

package com.OriginsB;

public class Tile {

     private static int ID;
     private static int Pos;

     public Tile(int ident, int Position){
        Pos = Position;
        ID = ident;
     }

     @Override
     public String toString(){
        return "Tile with ID: "+ID+" with pos: "+Pos;
     }
}

我得到了相同的输出:

Tile with ID: 4 with pos: 5
Tile with ID: 4 with pos: 5
Tile with ID: 4 with pos: 5
Tile with ID: 4 with pos: 5

帮助?

6 个答案:

答案 0 :(得分:2)

您已将IDPos声明为static,使其成为班级Tile的全球。如果您想要不同的输出,请删除static

private int ID;
private int Pos;

答案 1 :(得分:1)

那是因为你的变量是静态的。

这意味着如果您设置了值,它将适用于所有Tile实例。

更改为

private int ID;
private int Pos;

答案 2 :(得分:0)

删除staticID之前的Pos

答案 3 :(得分:0)

如下所示更改Tile.java

//删除了静态修改器。

public class Tile {

    private final int ID;
    private final int Pos;

    public Tile(int ident, int Position) {
        Pos = Position;
        ID = ident;
    }

    @Override
    public String toString() {
        return "Tile with ID: " + ID + " with pos: " + Pos;
    }

<强>输出

Tile with ID: 1 with pos: 2
Tile with ID: 2 with pos: 3
Tile with ID: 3 with pos: 4
Tile with ID: 4 with pos: 5

答案 4 :(得分:0)

static您不需要IDPos可以使用此代码:

private int ID;
private int Pos;

答案 5 :(得分:0)

问题是Tile类字段是STATIC。因为他们为类创建的不是每个类实例。更改的Tile类的工作代码如下:

public class Tile {

    private int ID;
    private int Pos;

    public Tile(int ident, int Position){
        Pos = Position;
        ID = ident;
    }

    @Override
    public String toString(){
        return "Tile with ID: "+ID+" with pos: "+Pos;
    }
}