如何将 Instant 转换为 Int

huangapple go评论75阅读模式
英文:

How to convert Instant to Int

问题

在我的应用程序中,我使用AlarmManager来设置预定通知。

为了让每个项目拥有唯一的通知,我需要为每个待定意图设置唯一的ID,否则通知会彼此重叠。

我的问题是,我的主键是字符串,而不是整数。我在项目模型中与整数最接近的是Instant,它表示应发送通知的时间,而且是唯一的。

由于PendingIntent的ID只是一个整数,我该如何将Instant转换为整数呢?
还是我应该采取另一种方法,在我的模型中创建一个数据字段来保存待定意图的ID?

据我理解,我不应直接将其转换,因为这将干扰日期/时间,而且可能(?)不会是唯一的。

英文:

In my app I have AlarmManager to set Scheduled notification.

In order to have unique notification to each Item, I need to set unique id to each pending intent, otherwise the notification run over each other.

my problem is that my PK is string, not an int. my closest thing to Int in my Item model is Instant, which represent the time that the notification should send, and It's unique.

And because PendingIntent id is only an int, how can I convert Instant to Int?
Or should I take another approach and create data field in my model just to hold the pending intent ID?

In my understanding I shoudn't convert it directly cause it will mess with the date/time and potentially(?) won't by unique

答案1

得分: 1

这应该可以运行,我认为:

instant.get(ChronoField.INSTANT_SECONDS)
英文:

That should work I think:

instant.get(ChronoField.INSTANT_SECONDS)

答案2

得分: 0

简单的字符串转整数可以使用 hashCode 完成。但是,哈希码在定义上不是唯一的。如果可能的话,将类型从 int 更改为 String 可能是最佳选择。如果您真的需要进行转换,我建议您创建类似于 IndexProvider 的东西。

public interface IndexProvider {

    /**
     * 用于 id 转换的幂等索引提供程序。
     * 请注意内存消耗,因为实现允许缓存 id。
     * @param id 唯一的 id
     * @return 已缓存的唯一 id 或新的唯一 id
     */
    int getIndex(String id);

}

这将允许您轻松解决问题。您可以在实现中使用映射来保存 String id。另一个想法是在数据库中解决这个问题。例如,可以创建一个新表,为每个 String id 存储一个 int id。最终,您将不得不修改某些内容,每种方法都会有优缺点。

这可能不是完整的答案,但我没有足够的声望来进行评论。

英文:

Simple String to int conversion could made with hashCode. But a hash code is by definition not unique. If possible then changing the type from int to String is probably the best option. If you really need a conversion I would recommend you create something like and IndexProvider.

public interface IndexProvider {

    /**
     * Idempotent index provider for id conversion.
     * Be aware of memory consumption because the implementations are allowed to cache id's.
     * @param id unique id
     * @return a cached unique id or a new unique id
     */
    int getIndex(String id);

}

This would allow you to simple solve the problem. You could use a map in the implementation for holding the String id's . Other idea would be to solve this problem in the database. For example a new table which holds you an int id for every String id. At the end you will have to modify something and you will have Pro's and Contra's for every approach.

This is probably not a full answer but I have not enough reputation for commenting.

huangapple
  • 本文由 发表于 2020年10月27日 21:27:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/64555490.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定