当使用相应的值代替时如何获取密钥?
我使用的是 Android 2.1 SDK,应用程序从 Sqlite 数据库读取,该表有两列、一个 id 和一个字符串。
我将其读入HashMap
,它的值部分显示在列表中,现在,我希望获取键值,所以我编写了这个简单的例程
private Map.Entry<Long, String> getEntry(String sValue){
for (Iterator<Map.Entry<Long, String>> itMap = this.dbMap.entrySet().iterator(); itMap.hasNext();) {
Map.Entry<Long, String> curr = itMap.next();
if (curr.getValue().equalsIgnoreCase(sValue)) return curr;
}
return null;
}
:问题是,在查找 HashMap 中的值时,要注意 Android、电池/CPU 时间等方面的 cpu 周期会被消耗,这可能被视为潜在的 cpu 周期丢失。
有没有一种比迭代更简单、更有效的方法来做到这一点?
原因是我可以根据id,直接从表中删除记录,甚至更新它。
I am using Android 2.1 SDK, the application reads from the Sqlite database, a table that has two columns, an id, and a string.
I read in this into a HashMap<Long, String>
, the value part of it gets displayed in a List, now, I wish to obtain the key value, so I cooked up this simple routine:
private Map.Entry<Long, String> getEntry(String sValue){
for (Iterator<Map.Entry<Long, String>> itMap = this.dbMap.entrySet().iterator(); itMap.hasNext();) {
Map.Entry<Long, String> curr = itMap.next();
if (curr.getValue().equalsIgnoreCase(sValue)) return curr;
}
return null;
}
My problem is being conscious of cpu cycles being chewed up in respect to Android, battery/cpu time, in looking for the value in the HashMap
, that could be seen as a potential cycles of cpu lost.
Is there an easier and more efficient way of doing this instead of iterating?
The reasoning is that I can home in on the id, and directly delete the record from the table or even update it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
嗯...看起来 String 应该是键,id 是值。它假设字符串是唯一的,但您的代码也是如此。
或者,您的列表不能以不可见的方式保留与条目相对应的 ID 吗?您通常会这样做(例如在 Swing 或 HTML 选择中)。
Um... it looks like the String should be the key, and the id the value. Which assumes that the Strings are unique, but so does your code.
Alternatively, can't your list keep the ID that corresponds to an entry around invisibly? This is how you'd usually do it (e.g. in Swing or in a HTML select).
实际上,避免迭代的唯一方法是保留两个 HashMap(即支付内存成本),其中一个 HashMap 与第一个相反。您可以在创建正向查找 HashMap 时创建反向查找 HashMap,而无需循环访问数据两次。这将为您提供两个方向的低恒定时间访问。
Realistically, the only way to avoid having to iterate through is to keep two HashMaps (i.e. pay the memory cost) where one HashMap is the reverse of the first. You can create the reverse-lookup HashMap when you create your forward-lookup HashMap without having to loop through your data twice. That should give you low constant time access in both directions.
如果您使用
适配器
< /a> 您可以使用getItemID()
方法访问 ID。If you use an
Adapter
you can access the ID using thegetItemID()
method.