Java:将字符串哈希为数字


#Java 笔记


使用 hashCode

示例代码:

public class Test {  
  
    public static void main(String[] args) {  
        String s = "aa";  
        int hashCode = s.hashCode();  
        System.out.println(hashCode);  
        System.out.println("aaa".hashCode());  
    }
}

执行结果:

3104
96321

使用 CRC32

示例代码:

import java.util.zip.CRC32;  
import java.util.zip.Checksum;  
  
public class Test {  
  
    public static void main(String[] args) {  
        String s = "aa";  
        byte[] bytes = s.getBytes();  
        Checksum crc32 = new CRC32();  
        crc32.update(bytes, 0, bytes.length);  
        long checkSum = crc32.getValue();  
        System.out.println(checkSum);  
    }
}

执行结果:

126491095


( 本文完 )