I want to implement a Hash function that takes a generic and generates a hash. The fun开发者_JAVA技巧ction will work at bit level, moving bits and stuff like that.
How can I do it? I thought about using an array of bytes, but how do I convert a generic argument to an array of bytes? Is there a better approach?
Thanks in advance
No, there's no way to treat an arbitrary object as a byte array in Java. That ability would cut a huge whole in the entire concept of type safety and even code safety, as it would allow arbitrary manipulatons of objects even outside the specification of their types.
You can convert a limited subset of objects to a byte stream using serialization, but the classes would have to support that (basically by implementing Serializable
).
Why not just override hashCode() in the classes (I'm assuming we're talking about classes you created), and do whatever you wish within hashCode(). I'm not sure where you plan on putting this "Hash function" you speak of. A utility method?
All objects in Java have a .hashCode()
. You can just use that as your "bits" to work with.
精彩评论