0

I am creating foreground notification with ID like so: startForeground(1, notification)

When initialising the service I am sending to it some string (ex: Hello). I wish that the service and notification will be bind to this string so I wish to use it as my id. So, how can I convert string to unique ID? For example the word "Hello" will always generate 123 And the word Bye will always generate 456.

4
  • Does it matter what the ID is, or just that it's unique? Should this value be persisted between runs? (i.e., if you restart the service, can "Hello" get a different ID, or should it always be the same one)? Commented Dec 6, 2020 at 12:45
  • Should be the same one. Commented Dec 6, 2020 at 12:46
  • 1
    you can use ascii value of the character to get a sum Commented Dec 6, 2020 at 12:49
  • If you need to use arbitrary strings, maybe just the string's hashcode? It's a number derived from its content (the character sequence basically). If you have a fixed set of strings and want a specific ID to associate with each, maybe creating an enum would be better - you can just use its ordinal as a unique ID, or set one in the constructor Commented Dec 6, 2020 at 19:38

1 Answer 1

1

That sounds like you want a "Hash Code"; a value derived from some other information that is (hopefully, but not always) unique.

There are a lot of different algorithms available to do this and if you search for "hash code" you will find lots of them (especially in the security domain; sha, md5 etc)

However, It sounds like you may not really need to get that complex (some of the more secure and "unique" hash code algorithms can be slow to calculate). Is there any reason why you can't use the string itself?

String comparison may be slow, but maybe not as slow as a good hash. Also you might be able to use a Hash Table if you need a faster "lookup".. hashmap

Anyway, if you really do need a hash code from a string, a quick search found this (which looks reasonable) Sam Clarke; Kotlin Hash Strings

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.