将通用参数仅视为“位”
我想实现一个哈希函数,它采用泛型并生成哈希。该函数将在位级别工作,移动位之类的东西。
我该怎么做呢?我考虑过使用字节数组,但是如何将通用参数转换为字节数组?有更好的方法吗?
提前致谢
I want to implement a Hash function that takes a generic and generates a hash. The function 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,Java 中没有办法将任意对象视为字节数组。这种能力将极大地削弱类型安全甚至代码安全的整个概念,因为它允许对对象进行任意操作,甚至超出其类型规范。
您可以使用序列化将有限的对象子集转换为字节流,但类必须支持这一点(基本上通过实现
Serialized
)。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
).为什么不直接重写类中的 hashCode() (我假设我们正在讨论您创建的类),并在 hashCode() 中执行您希望执行的任何操作。我不确定你打算把你所说的这个“哈希函数”放在哪里。实用方法?
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?
Java 中的所有对象都有一个
.hashCode()
。您可以将其用作您要使用的“位”。All objects in Java have a
.hashCode()
. You can just use that as your "bits" to work with.