Sebastian Kruk
Sebastian Kruk

Reputation: 27

Can i create object of my class containing array?

I have small problem with my code. Can I put a table (array) in the class constructor? When I put types like int/string my class works perfectly but when I try put an array int[][]into the constructor of every object of my class, it always returns the last value of the array. Is there a way to put a table (array) inside the constructor?

Example code:

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

}

And using it:

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

This returns only the last added table (array)... Objects of course do not contain the same table (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();
            }

Upvotes: 1

Views: 1190

Answers (1)

Giulio Biagini
Giulio Biagini

Reputation: 920

It depends on how you initialise your Population object:

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();
    }
}

And the output is:

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

Upvotes: 1

Related Questions