GetHashCode () проблема с помощью xor

Понятия не имею о SwiftyJSON. Я использую следующий фрагмент кода для преобразования между json и nsdata

// Convert from NSData to json object
public class func nsdataToJSON(data: NSData) -> AnyObject? {
    return NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil)
}

// Convert from JSON to nsdata
public class func jsonToNSData(json: AnyObject) -> NSData?{
    return NSJSONSerialization.dataWithJSONObject(json, options: .allZeros, error: nil)
}
9
задан Community 23 May 2017 в 11:55
поделиться

6 ответов

First off - Do not implement Equals() only in terms of GetHashCode() - hashcodes will sometimes collide even when objects are not equal.

The contract for GetHashCode() includes the following:

  • different hashcodes means that objects are definitely not equal
  • same hashcodes means objects might be equal (but possibly might not)

Andrew Hare suggested I incorporate his answer:

I would recommend that you read this solution (by our very own Jon Skeet, by the way) for a "better" way to calculate a hashcode.

No, the above is relatively slow and doesn't help a lot. Some people use XOR (eg a ^ b ^ c) but I prefer the kind of method shown in Josh Bloch's "Effective Java":

public override int GetHashCode()
{
 int hash = 23;
 hash = hash*37 + craneCounterweightID;
 hash = hash*37 + trailerID;
 hash = hash*37 + craneConfigurationTypeCode.GetHashCode();
 return hash;
}

The 23 and 37 are arbitrary numbers which are co-prime.

The benefit of the above over the XOR method is that if you have a type which has two values which are frequently the same, XORing those values will always give the same result (0) whereas the above will differentiate between them unless you're very unlucky.

As mentioned in the above snippet, you might also want to look at Joshua Bloch's book, Effective Java, which contains a nice treatment of the subject (the hashcode discussion applies to .NET as well).

28
ответ дан 4 December 2019 в 06:57
поделиться

Эндрю опубликовал хороший пример генерации лучшего хэш-кода, но также имейте в виду, что вы не должны использовать хеш-коды для проверки равенства, поскольку их уникальность не гарантируется.

Тривиальный пример того, почему это двойной объект. У него больше возможных значений, чем у int, поэтому невозможно иметь уникальный int для каждого типа double. Хэши на самом деле являются всего лишь первым проходом, используемым в таких ситуациях, как словарь, когда вам нужно быстро найти ключ, сначала сравнивая хеши, можно исключить большой процент возможных ключей, и только ключи с совпадающими хешами должны иметь расходы полной проверки равенства (или другие методы разрешения конфликтов ).

2
ответ дан 4 December 2019 в 06:57
поделиться

Out of curiosity since hashcodes are typically a bad idea for comparison, wouldn't it be better to just do the following code, or am I missing something?

public override bool Equals(object obj)
{
    bool isEqual = false;
    Foo otherFoo = obj as Foo;
    if (otherFoo != null)
    {
        isEqual = (this.A == otherFoo.A) && (this.B == otherFoo.B);
    }
    return isEqual;
}
0
ответ дан 4 December 2019 в 06:57
поделиться

Чтение Переопределение GetHashCode для изменяемых объектов? C # и подумайте о реализации IEquatable

1
ответ дан 4 December 2019 в 06:57
поделиться

Есть несколько лучших реализаций хеширования. Хеш FNV , например.

0
ответ дан 4 December 2019 в 06:57
поделиться

Хеширование всегда связано с коллизиями, и вы должны иметь дело с этим (например, сравните хеш-значения и, если они равны, точно сравните значения внутри классов, чтобы убедиться, что классы равны).

Используя простой XOR, вы получите много коллизий. Если вы хотите меньше, используйте математические функции, которые распределяют значения по разным битам (битовые сдвиги, умножение на простые числа и т. Д.).

1
ответ дан 4 December 2019 в 06:57
поделиться
Другие вопросы по тегам:

Похожие вопросы: