gpt4 book ai didi

java - 在java中转换列表<>?

转载 作者:行者123 更新时间:2023-12-02 14:06:05 27 4
gpt4 key购买 nike

您好,可以转换列表吗?

我有一个抽象类,它有一个接受某种 List<> 的方法,在 for 循环中迭代它,获取该列表中的每个对象,并调用子类实现的 insertItem 抽象方法来基本上拉取取出项目中的正确数据,然后最终将它们插入数据库表中。

这是父类(super class)方法:

protected void insertAllItemsToDb(List<Object> items, String table) {
// open db and table

database().beginTransaction();
// clear all data from table
clearTable(table);
// call a insert statement to insert each column from an item
for (Object object : items) {
insertItem(object, table);
}
// close db
database().endTransaction();
database().close();
}

在子类中,这里是重写方法之一:我可以在这里很好地转换对象。

  @Override
protected void insertItem(Object object, String table) {

CalendarEventItem item = (CalendarEventItem) object;
eventItemValue = new ContentValues();

eventItemValue.put(LABEL_EVENTS_TITLE, item.getEventTitle());
eventItemValue.put(LABEL_EVENTS_LOCATION, item.getEventLocation());
eventItemValue.put(LABEL_EVENTS_DATE, item.getEventStartTime()
.getDate());
eventItemValue.put(LABEL_EVENTS_TIME, item.getEventStartTime()
.getTime());
eventItemValue.put(LABEL_EVENTS_TIMEZONE, item.getEventStartTime()
.getTimeZone());

database.insert(TABLE_NAME_EVENTS, null, eventItemValue);

}

然后我使用以下方法从父类(super class)调用该方法:

events =  (List<CalendarEventItem>) items;
insertAllItemsToDb(events, TABLE_NAME_EVENTS);

但是我收到一个编译错误,说你无法转换它。有关如何实现此目的的任何想法,而无需重复您在 insertAllItemsToDb() 中看到的相同步骤和代码

最佳答案

使用类型参数

向抽象类添加通用参数:

public abstract class BaseClass<T>{

protected abstract void insertItem(T object, String table);

protected void insertAllItemsToDb(List<T> items, String table) {
//...
for (T object : items) {
insertItem(object, table);
}
//...
}

}

现在您不需要任何转换,子类只需使用正确的类型:

public class FooBar extends BaseClass<Phleem>{
protected void insertItem(Phleem object, String table){
// ...
}

}

关于java - 在java中转换列表<>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4034262/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com