-6

Why my Model class data is incorrect?

enter image description here

List<DataMasterList> dataMasterLists = new ArrayList<DataMasterList>();

private void addMaster() {
    for (int i = 0; i < 6; i++) {
        DataMasterList dataMasterList = new DataMasterList();
        dataMasterList.setMaster_code("000" + i);
        dataMasterList.setProduct_name("name" + i);
        dataMasterList.setAmount(4 + i + "");
        dataMasterList.setUnit_price(10 + "");
        dataMasterLists.add(dataMasterList);
        Log.d("test1",dataMasterLists.get(i).getMaster_code()+" ");
    }

    Log.d("test2",dataMasterLists.get(0).getMaster_code()+" ");
}

Content of Log.d:

test1: 0000
test1: 0001
test1: 0002
test1: 0003
test1: 0004
test1: 0005

test2: 0005

Why does test2 = 0005 ?

Why every value in dataMasterLists is 0005 ?

aUserHimself
  • 1,589
  • 2
  • 17
  • 26

1 Answers1

0

The problem is about access modifiers which change the fields class behaviour . You are making confusion with class instance variable and class variable .

Case 1 (instance variable )

public class DataMasterList {

    private String masterCode;

    public DataMasterList() {
        // TODO Auto-generated constructor stub
    }

    public  String getMasterCode() {
        return this.masterCode;
    }

    public  void setMasterCode(String masterCode) {
        this.masterCode = masterCode;
    }

private String masterCode; you can access to this field only with accessor methods and when you create a new instance , each instance will have own field.

case 2 (static variable )

public class DataMasterList {

    static String masterCode;

    public DataMasterList() {
        // TODO Auto-generated constructor stub
    }

    public static String getMasterCode() {
        return masterCode;
    }

    public static void setMasterCode(String masterCode) {
        DataMasterList.masterCode = masterCode;
    }

} 

static String masterCode; you can access to the field directly without accessor methods and without create any instance of the object . Anyway if you create instances like in your case , when you modify the last time the masterCode it willl effect all instances.

Frank
  • 873
  • 1
  • 7
  • 17