java array loop issue
本问题已经有最佳答案,请猛点这里访问。
我有一个特殊的问题,当在数组中分配循环中的元素时,事情会发生。
当我移出循环并检查时,所有索引的相同数组值将被设置为最后一个索引的值。下面是代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | JSONObject js = new JSONObject(json_string); JSONArray jsonArray=js.getJSONArray("customer"); DataModelCollection[] dataModelCollection = new DataModelCollection[7]; for (int i=0;i<jsonArray.length();i++) { JSONObject json = jsonArray.getJSONObject(i); amont = json.getLong("BalanceAmount"); custName = json.getString("CustName"); partitionKey = json.getInt("PartitionKey"); String date1 = json.getString("date"); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = df.parse(date1); dataModelCollection[i] = new DataModelCollection(); dataModelCollection[i].setName(custName); dataModelCollection[i].setAccountNo(partitionKey); dataModelCollection[i].setAmount(amont); dataModelCollection[i].setCollectedDate(date); Log.i("inside_loop",""+dataModelCollection[i].getName()); } Log.i("outside_loop",""+dataModelCollection[0].getName()); Log.i("outside_loop",""+dataModelCollection[1].getName()); Log.i("outside_loop",""+dataModelCollection[2].getName()); Log.i("outside_loop",""+dataModelCollection[3].getName()); Log.i("outside_loop",""+dataModelCollection[4].getName()); Log.i("outside_loop",""+dataModelCollection[5].getName()); Log.i("outside_loop",""+dataModelCollection[6].getName()); |
当我打印
不知道我哪里弄错了。
不管它的价值是什么,这里的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | public class DataModelCollection { public static long accountNo; public static String name; public static double amount; public static Date collectedDate; public DataModelCollection(long accountNo, String name, double amount, Date collectedDate) { this.accountNo = accountNo; this.name = name; this.amount = amount; this.collectedDate = collectedDate; } public DataModelCollection() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public Date getCollectedDate() { return collectedDate; } public void setCollectedDate(Date collectedDate) { this.collectedDate = collectedDate; } public long getAccountNo() { return accountNo; } public void setAccountNo(long accountNo) { this.accountNo = accountNo; } |
我真的不知道是什么导致了这种情况。请帮忙。
1 2 3 4 |
这些需要是实例变量,而不是静态变量。
删除
用俗语来说,"静态"在Java中意味着什么?
让我教你一些魔法吧!
删除在类DataModelCollection中声明的变量中的关键字static,代码工作正常。
您的
您必须从其中每一个中删除关键字
1 2 3 4 |
到
它们都成为最后一个设置值的原因是因为