0

我正在尝试创建大小动态的数组列表,添加元素并在完成时遍历它们。目前我的代码是:

    String activities = "SELECT DISTINCT phoneactivity from ContextTable030313";
    ArrayList<String> myActivities = new ArrayList();

    Cursor cursor2 = db.rawQuery(activities, null);
    // looping through all rows and adding to list
    if (cursor2.moveToFirst()) {
        do {
            myActivities.add(cursor.getString(cursor2.getColumnIndex("ts")));

        } while (cursor2.moveToNext());
    }

然而它无法在 do 循环中运行。我相信我声明不正确,我收到以下警告:

- ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized
    - Avoid object allocations during draw/layout operations (preallocate and reuse instead)
    - Type safety: The expression of type ArrayList needs unchecked conversion to conform to 
     ArrayList<String>

但我不明白为什么这不起作用。

4

2 回答 2

1

问题似乎是这样的:

类型安全:ArrayList 类型的表达式需要未经检查的转换才能符合 ArrayList

这指出了这行代码:

ArrayList<String> myActivities = new ArrayList();

您应该将该行更改为:

ArrayList<String> myActivities = new ArrayList<String>();

另一方面,您可以替换此代码段:

  if (cursor2.moveToFirst()) {
        do {
            myActivities.add(cursor.getString(cursor2.getColumnIndex("ts")));

        } while (cursor2.moveToNext());
    }

有了这个:

  while (cursor2.moveToFirst()) {       
        myActivities.add(cursor.getString(cursor2.getColumnIndex("ts")));       
    }
于 2013-03-05T06:39:05.287 回答
0

更改您的 arrayList 声明,使其在构造函​​数调用期间接受参数化类型

ArrayList<String> myActivities = new ArrayList<String>();

如果您使用 java 7 或更高版本:

ArrayList<String> myActivities = new ArrayList<>();

由于*类型推断*,您不需要在构造函数调用期间声明参数化类型,但您仍然需要声明空<>。

于 2013-03-05T06:38:27.427 回答