【问题标题】:Which hash function does java.io.Serializable uses?java.io.Serializable 使用哪个哈希函数?
【发布时间】:2015-01-26 22:45:40
【问题描述】:

我正在阅读其他人的 coe,并且有一个对象实现了 java.io.Serializable 函数:

import java.io.Serializable;

public class Pair<F, S> implements Serializable{

  private final F first;
  private final S second;

  public Pair(F f, S s)  {
    this.first = f;
    this.second = s;
  }

  public int hashCode()
  {
    int hashFirst = this.first != null ? this.first.hashCode() : 0;
    int hashSecond = this.second != null ? this.second.hashCode() : 0;

    return (hashFirst + hashSecond) * hashSecond + hashFirst;
  }



public boolean equals(Object obj)
  {
    if ((obj instanceof Pair))
    {
      Pair<?, ?> other = (Pair)obj;

      return ((this.first == other.first) || ((this.first != null) && (other.first != null) && (this.first.equals(other.first)))) && ((this.second == other.second) || ((this.second != null) && (other.second != null) && (this.second.equals(other.second))));
    }
    return false;
  }

}

this.first.hashCode()被hash时调用的hash函数是什么?是md5吗?

只是一个附带问题。 Pair&lt;F,S&gt; 是什么意思?为什么会有一个尖括号。

我的任务是将 java 类重新实现为 python 对象,现在我正在使用 md5 对代码进行哈希处理,但我不确定它是否相同。即:

import md5

class Pair:
    serialVersionUID = 4496923633090911746L
    def __init__(self, f, s):
        self.f = f
        self.s = s

    def hashCode(self):    
        hashFirst = 0 if self.f else self.f.__hash__()
        hashSecond = 0 if self.f else self.s.__hash__()
        return (hashFirst + hashSecond) * hashSecond + hashFirst

    def equals(self, other):
        if isinstance(Pair, other):
            first_is_same_object = self.f is other.f
            second_is_same_object = self.s is other.s 

            first_is_same_value = self.f == other.f 
            second_is_same_value = self.s == other.s

            no_none_value = None not in [self.f, other.f, self.s, other.s]

            same_value = no_none_value and second_is_same_value and first_is_same_value
            same_object = first_is_same_object and second_is_same_object

            return same_value or same_object
        else:
            return False

【问题讨论】:

    标签: java python serialization hash


    【解决方案1】:

    首先是你的标题问题。

    java.io.Serializable 使用哪个哈希函数?

    Serializable 不使用任何散列函数。它允许以后存储(序列化)和检索(反序列化)Java 对象。阅读serialization 在此处使用。

    对 this.first.hashCode() 进行哈希处理时调用的哈希函数是什么?是md5吗?

    Hashcode 是一个用于集合中对象比较和对象搜索的概念。 Python 有类似的概念__hash__,请阅读。它是一个对象的指纹,一个 int。 Hashcode 与 MD5 散列在概念上有相似之处,但它们的用途不同。

    对是什么意思?为什么会有一个尖括号。

    这些是Java generics implementation。在强类型语言中,泛型帮助编译器检查类中是否存在方法和其他特性。由于您的目标是将此类转换为 python(一种弱类型语言),因此这些检查将在运行时完成。

    【讨论】:

      猜你喜欢
      • 2012-06-04
      • 2010-11-19
      • 2011-05-12
      • 1970-01-01
      • 2010-11-12
      • 2012-05-09
      • 2013-03-07
      • 2014-03-11
      • 1970-01-01
      相关资源
      最近更新 更多