我正在尝试创建数组列表,动态大小,添加元素并在完成后迭代它们。目前我的代码是:
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>
但我不明白为什么这不起作用。
答案 0 :(得分: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")));
}
答案 1 :(得分:0)
更改您的arrayList声明,使其在构造函数调用期间接受参数化类型。
ArrayList<String> myActivities = new ArrayList<String>();
如果您使用java 7或更高版本:
ArrayList<String> myActivities = new ArrayList<>();
由于* 类型推断 *,您不需要在构造函数调用期间声明参数化类型,但仍需要声明空<&lt;&gt;。