Created
December 2, 2016 17:13
-
-
Save vladimirdolzhenko/df7b3426400b56d342dd87fd77507b6d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.ByteArrayInputStream; | |
import java.io.ByteArrayOutputStream; | |
import java.io.ObjectInputStream; | |
import java.io.ObjectOutputStream; | |
import java.io.Serializable; | |
/** | |
* @author vladimir.dolzhenko | |
* @since 2016-12-02 | |
*/ | |
public class S implements Serializable { | |
private final byte[] values; | |
private transient final int hashCode; | |
public S(byte[] values) { | |
this.values = values; | |
this.hashCode = calcHashCode(values); | |
} | |
private static int calcHashCode(final byte[] bytes) { | |
int hc = 17; | |
for (byte b : bytes) { | |
hc = (hc << 4) + hc + higher(b); | |
} | |
return hc; | |
} | |
public byte[] getValues() { | |
return values; | |
} | |
public int getHashCode() { | |
return hashCode; | |
} | |
private static int higher(byte b) { | |
return b & (b >= 'a' && b <= 'z' ? 0xDF : 0xFF); | |
} | |
Object readResolve() { | |
return new S(this.values); | |
} | |
public static void main(String[] args) throws Exception { | |
final S s = new S("XXX".getBytes()); | |
final ByteArrayOutputStream bos = new ByteArrayOutputStream(); | |
ObjectOutputStream os = new ObjectOutputStream(bos); | |
os.writeObject(s); | |
os.flush(); | |
os.close(); | |
final ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); | |
final ObjectInputStream ois = new ObjectInputStream(bis); | |
S s2 = (S) ois.readObject(); | |
System.out.println(s.getHashCode()); | |
System.out.println(s2.getHashCode()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment