我可以创建包含数组的类的对象吗?

时间:2015-01-26 11:59:37

标签: java

我的代码存在小问题。我可以在类构造函数中放置一个表(数组)吗?当我把类似int / string的类型运行得很完美但是当我尝试将数组int[][]放入我的类的每个对象的构造函数中时,它总是返回数组的最后一个值。有没有办法将表(数组)放在构造函数中?

示例代码:

public class Population {
 int[][] population_object;
 int test;  

public Population(int[][] population_object){
    this.population_object = population_object;
}


public int[][] population_print(){
    return this.population_object;
    }

}

使用它:

static ArrayList<Population> population_list;
population_list = new ArrayList<Population>();
Population buff = new Population(pupulation_object_buffor);
population_list.add(buff);

这只返回最后添加的表(数组)...对象当然不包含相同的表(population_object_buffor)

int[][] test = population_list.get(s).population_print();

for(int k=0; k<test.length; k++){
                for(int kk=0; kk<test[k].length; kk++){
                    System.out.print(" "+test[k][kk]);
                }
                System.out.println();
            }

1 个答案:

答案 0 :(得分:1)

这取决于您初始化Population对象的方式:

public class Population
{
    private int[][] object;

    public Population(int[][] object) {
        this.object = object;
    }

    public void print() {
        for (int i = 0; i < object.length; i++) {
            for (int j = 0; j < object[i].length; j++)
                System.out.print(object[i][j]);
            System.out.println();
        }
    }
}



public static void main(String[] args) {
    ArrayList<Population> population = new ArrayList<>();

    // 5 Population
    for (int nr = 1; nr <= 5; nr++) {
        // each Population has an int[5][5]
        int[][] object = new int[5][5];
        // int the object
        for (int i = 0; i < 5; i++)
            for (int j = 0; j < 5; j++)
            object[i][j] = nr;
        // add the Population with the object just created
        population.add(new Population(object));
    }

    // print out each Population object
    for (int i = 0; i < population.size(); i++) {
        System.out.println("Population " + (i + 1) + ":");
        population.get(i).print();
        System.out.println();
    }
}

输出是:

Population 1:
11111
11111
11111
11111
11111

Population 2:
22222
22222
22222
22222
22222

Population 3:
33333
33333
33333
33333
33333

Population 4:
44444
44444
44444
44444
44444

Population 5:
55555
55555
55555
55555
55555