gpt4 book ai didi

java - HashMap(它)会做什么?

转载 作者:行者123 更新时间:2023-12-01 17:53:49 24 4
gpt4 key购买 nike

我正在学习《Kotlin for androiddevelopments》的示例代码,地址:https://github.com/antoniolg/Kotlin-for-Android-Developers

代码中.parseList { DayForecast(HashMap(it)) } ,我不明白函数 HashMap(it) 会做什么。 HashMap() 是一个类并接受参数 it

还有,我认为类DayForecast(...)..的完整代码是代码A,对吗?

同样,如果我创建一个对象 var myDayForecast=DayForecast(10L,"Desciption",10,5,"http://www.a.com",10L) ,myDayForecast.map 会是空的吗?

代码A

class DayForecast(var map: MutableMap<String, Any?>) {
var _id: Long by map
var date: Long by map
var description: String by map
var high: Int by map
var low: Int by map
var iconUrl: String by map
var cityId: Long by map

constructor(date: Long, description: String, high: Int, low: Int, iconUrl: String, cityId: Long)
: this(map: MutableMap<String, Any?>=HashMap()) {
this.date = date
this.description = description
this.high = high
this.low = low
this.iconUrl = iconUrl
this.cityId = cityId
}
}

原始代码

override fun requestForecastByZipCode(zipCode: Long, date: Long) = forecastDbHelper.use {

val dailyRequest = "${DayForecastTable.CITY_ID} = ? AND ${DayForecastTable.DATE} >= ?"
val dailyForecast = select(DayForecastTable.NAME)
.whereSimple(dailyRequest, zipCode.toString(), date.toString())
.parseList { DayForecast(HashMap(it)) }

val city = select(CityForecastTable.NAME)
.whereSimple("${CityForecastTable.ID} = ?", zipCode.toString())
.parseOpt { CityForecast(HashMap(it), dailyForecast) }

city?.let { dataMapper.convertToDomain(it) }
}


class DayForecast(var map: MutableMap<String, Any?>) {
var _id: Long by map
var date: Long by map
var description: String by map
var high: Int by map
var low: Int by map
var iconUrl: String by map
var cityId: Long by map

constructor(date: Long, description: String, high: Int, low: Int, iconUrl: String, cityId: Long)
: this(HashMap()) {
this.date = date
this.description = description
this.high = high
this.low = low
this.iconUrl = iconUrl
this.cityId = cityId
}
}

最佳答案

我认为从答案here ,你应该已经明白 parseList 提供了闭包 { DayForecast(HashMap(it)) } Map 对象。

但是正如您现在显示的定义 DayForecast

class DayForecast(var map: MutableMap<String, Any?>)

需要 MutableMap

MutableMap 之间的主要区别和一个 Map那是Map无法更改,而 MutableMap可以改变。

原因DayForecast需要 MutableMap是因为在辅助构造函数中传入了对象,称为map被改变(突变)。这是您最近的其他部分question .

HashMapMutableMap 的基于哈希表的实现接口(interface),因此可以使用 MutableMap预计。

总结一下:

DayForecast() 期望 MutableMap对象传递给它的主构造函数,但 parseList 仅提供 Map到它收到的闭包,所以解决方案是插入 HashMap()创建 MutableMap .

这也应该回答您在评论中提出的问题,为什么 parseList 不能只采用闭包 { DayForecast(it) }而不是{ DayForecast(HashMap(it)) } ?这是因为如上面所示,DayForecast() 的构造函数需要 MutableMap ,其中it不是(它是 Map )而 HashMap(it)MutableMap .

关于java - HashMap(它)会做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47175077/

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