eclipse - Java: List and Array fill each other in wrong way -


i trying make program makes list of arrays different entries. there 2 classes: class1 shall contain array1 full of (seven) 0's; in class1 shall method fills list of 7 class2's; each of them shall contain array has 6 0's , 1 one @ different locations, this: class2 number1: 1, 0, 0, 0, 0, 0, 0. class2 number2: 0, 1, 0, 0, 0, 0, 0.

and on.

then, want print entries. should like:

1 0 0 0 0 0 0 (end of class2 number 1) 0 1 0 0 0 0 0 (end of clas2 number 2) , on, until prints array of 1 , instance of class1 used. 0 0 0 0 0 0 0

but instead, prints long row of 1's.

my code:

class1:

import java.util.arraylist; import java.util.list;  public class class1{      int[] array1 = new int[7];      public class1(){          (int = 0; < 7; i++){             array1[i] = 0;         }     }      public list<class2> list(){          list<class2> returnlist = new arraylist<class2>();          (int = 0; < 7; i++){              returnlist.add(new class2(array1, i, 1));          }          return returnlist;     }  } 

second class:

public class class2{      int[] array2 = new int[7];      public class2(int[] array, int index, int number){          array2 = array;          if (index >= 0 && index < array2.length){             array2[index] = number;         }      } } 

main class:

public class main{      public static void main (string[] args){          class1 class1 = new class1();         (int = 0; < 7; i++){             (int j = 0; j < 7; j++){             system.out.println(class1.list().get(i).array2[j]);         }     }      (int = 0; < 7; i++){         system.out.println(class1.array1[i]);     } }  } 

when create objects of class2 assigning array of class1 each object of class2: array2 = array;

arrays not handed on value, instead reference. therefore each class2 object writing 1 in same array used classes. have explicitely create new array each class2 object (which already) , copy values array parameter.

public class2(int[] array, int index, int number){     (int = 0; < array.length; i++) {         array2[i] = array[i];     }     if (index >= 0 && index < array2.length){         array2[index] = number;     } } 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -