List <string> = new ArrayList()vs ArrayList&lt;&gt;()

时间:2015-12-20 14:32:55

标签: java android arraylist

List<Event> eventList = new ArrayList();
String selectQuery = "SELECT  * FROM " + TABLE_EVENTS+" WHERE " +  KEY_TYPE+" = \""+type_+"\"";
db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
            do {

                // event.setID(Integer.parseInt(cursor.getString(0)));
                event.setName(cursor.getString(1));

                event.setDescription(cursor.getString(7));
                event.setLink(cursor.getString(4));
                event.setLocation(cursor.getString(2));
                event.setType(cursor.getString(3));
                event.setStartDate(cursor.getString(5));
                event.setEndDate(cursor.getString(6));

                // Adding contact to list
                eventList.add(event);
               event.writeSc(event);

            } while (cursor.moveToNext());
        }
 db.close();
        return eventList;
    }

这里当我开始使用新的Arraylist时,它不起作用。打印时,值始终相同。但是当我做的时候

List<Event> eventList = new ArrayList<>();

它有效。

1 个答案:

答案 0 :(得分:-1)

问题不在于List的初始化。您的问题是一次又一次地向List添加相同的实例,因为您不会为添加到List中的每个元素创建新的Event实例。

        do {
            event = new Event; // here's what you are missing
            event.setName(cursor.getString(1));
            ...

对于List初始化,

List<Event> eventList = new ArrayList<>();

更正确,因为它使用泛型类型而不是原始ArrayList类型。