gpt4 book ai didi

Java:获取对象的唯一属性(如哈希码,但防碰撞)

转载 作者:行者123 更新时间:2023-11-29 09:51:15 24 4
gpt4 key购买 nike

我有一项任务需要为集合中的每个对象生成一个唯一值。如果哈希码合约中不允许发生冲突,则使用哈希码将是完美的。

一个想法:将每个对象的哈希码记录到一个多重集中。然后,使用哈希码作为唯一标识符,但如果该哈希码多次出现在集合中,则使用同样不在集合中的不同值。但这感觉笨重且笨拙。

更好的想法?

这是我已经拥有的:

public static <V> void toGraphViz(final Graph<V, DefaultWeightedEdge> g, String filename) {

// to avoid hashcode collisions
final Set<Integer> hashcodes = new HashSet<Integer>(g.vertexSet().size());

DOTExporter<V, DefaultWeightedEdge> dot = new DOTExporter<V, DefaultWeightedEdge>(new VertexNameProvider<V> () {

// vertex name must be unqiue
@Override
public String getVertexName(V arg0) {
int hash = arg0.hashCode();
while (hashcodes.contains((hash))) {
hash += 1;
}
return "" + hash;
}
}

编辑: 我想这最初并不清楚,但 id 号确实需要以某种方式成为对象的函数,因为 getVertexName(V) 将得到多次调用,它期望对于相同的 V 值,它会得到相同的结果。

此外,顶点类型是通用的。所以我无法对特定类进行任何修改来解决此问题。

最佳答案

这个唯一编号的生命周期是多少?只是程序的生命周期?在这种情况下,为什么不只是类中的一个简单的静态计数器,通过适当的同步访问?为每个新对象增加它。无需保留您使用过的值的列表,只需保留您使用过的最高值。

如果在许多执行(可能还有许多同时发生的实例)中是唯一的,那么也许您可以只使用一个数据库来生成唯一的记录 ID。

编辑以回应澄清

我之前错过的一点是我们不能修改我们想要为其生成唯一“哈希”的类。

我认为从类的哈希码开始工作会产生冲突,这让生活变得很艰难。假设我们可以依赖已正确实现 equals() 的相关 Vertex 类,那么我们可以使用对象本身作为我们使用的哈希码集的键。

public class Hasher {

public <V> void toGraphViz(final Graph<V, DefaultWeightedEdge> g, String filename) {
final Map<V, Integer> hashcodes = new HashMap< V, Integer>();
final int latestHashHolder[] = { 0 }; // array to allow access from inner class

DOTExporter<V, DefaultWeightedEdge> dot
= new DOTExporter<V, DefaultWeightedEdge>(new VertexNameProvider<V> ()) {

// vertex name must be unqiue
@Override
public synchronized String getVertexName(V vertex) {
int hashcode;
if ( hashcodes.containsKey(vertex)){
hashcode = hashcodes.get(vertex);
} else {
hashcode = latestHashHolder[0];
latestHashHolder[0]++;
hashcodes.put(vertex, (Integer)latestHashHolder[0]);
}
return "Vertex-" + hashcode;
}
};
}
}

关于Java:获取对象的唯一属性(如哈希码,但防碰撞),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1843565/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com