我正在使用一个 arrayList,我通过一个循环将数据库中的条目添加到。在该循环中,我用正在读取的行中的字段填充一个数组。我将此数组分配给arrayList。
我从今天的谷歌搜索中了解到,当我调用 arrayList.add() 时,我传递的是对数组的引用,而不是将数组复制到 arrayList 元素中。这不是我想要的。
有什么更好的方法来解决这个问题?
Cursor cursor = this.managedQuery(Record.Records.CONTENT_URI, projection, Record.Records.START_TIME + " > " + 1, null, Record.Records.START_TIME + " ASC");
int i, n, x = 0;
List<String[]> sleepCollection = new ArrayList<String[]>();
String[] sleepItem = new String[7];
for (i=0;i<cursor.getCount();i++)
{
if (i==0)
cursor.moveToFirst();
for (n=0;n<5;n++)
sleepItem[n] = cursor.getString(n);
// hours, duration
sleepItem[5] = String.valueOf((((Long.valueOf(sleepItem[1])-Long.valueOf(sleepItem[0]))/1000)+(Long.valueOf(sleepItem[4])*60))/60/60);
// minutes, duration
sleepItem[6] = String.valueOf((((Long.valueOf(sleepItem[1])-Long.valueOf(sleepItem[0]))/1000)+(Long.valueOf(sleepItem[4])*60))/60%60);
if ( (x > 0) &&
(Long.valueOf(sleepCollection.get(x-1)[1]) - Long.valueOf(sleepItem[0]) <= 7200000) // record started within 2 hours if end of previous record
)
{
// set rating
sleepCollection.get(x-1)[2] = String.valueOf((Float.valueOf(sleepCollection.get(x-1)[2])) + Float.valueOf(sleepItem[2]) / 2);
sleepCollection.get(x-1)[1] = sleepItem[1]; // set previous record's end date equal to current record's end date
// then add duration of previous record to current record (hours, then minutes)
sleepCollection.get(x-1)[5] = String.valueOf(Integer.valueOf(sleepItem[5])+Integer.valueOf(sleepCollection.get(x-1)[5]));
sleepCollection.get(x-1)[6] = String.valueOf(Integer.valueOf(sleepItem[6])+Integer.valueOf(sleepCollection.get(x-1)[6]));
// check if minutes are 60 or over
if (Integer.valueOf(sleepCollection.get(x-1)[6]) >= 60)
{
// if so, subtract 60 from minutes
sleepCollection.get(x-1)[6] = String.valueOf(Integer.valueOf(sleepCollection.get(x-1)[6]) - 60);
// and add an hour to hours
sleepCollection.get(x-1)[5] = String.valueOf(Integer.valueOf(sleepCollection.get(x-1)[5]+1));
}
}
else
{
// this passes a reference of sleepItem. I want sleepCollection to actually contain the array and not a reference to it. What's the best way to do that?
sleepCollection.add(sleepItem);
x++;
}