Java Constructor hashCode()方法及示例
java.lang.reflect.Constructor类 的 hashCode() 方法用于返回该Constructor对象的哈希码。如果构造对象没有变化,那么哈希码总是相同的。哈希码是在类对象创建时由JVM生成的唯一代码。我们可以使用哈希码来对哈希相关的算法进行一些操作,如哈希表、哈希图等。我们可以用这个唯一的代码来搜索一个对象。
语法
public int hashCode()
参数: 此方法不接受任何东西。
返回 :该方法为该对象返回一个哈希代码的 整数 值。
以下程序说明了hashCode()方法:
程序1 :
// Java program to illustrate hashCode() method import java.lang.reflect.Constructor;import java.util.ArrayList; public class GFG { public static void main(String[] args) { // create a class object Class classObj = ArrayList.class; // get Constructor object // array from class object Constructor[] cons = classObj.getConstructors(); // get hash code of this constructor class int code = cons[0].hashCode(); // print result System.out.println( "Hash Code count = " + code); }}
输出。
Hash Code count = -1114099497
程序2
// Java program to illustrate hashCode() method import java.lang.reflect.Constructor; public class GFG { public static void main(String[] args) { // create a class object Class classObj = String.class; // get Constructor object // array from class object Constructor[] cons = classObj.getConstructors(); // get hash code of this constructor class int code = cons[0].hashCode(); // print result System.out.println( "Hash Code count for string class" + " constructor = " + code); }}输出。
Hash Code count for string class constructor = 1195259493
参考文献: https://docs.oracle.com/javase/10/docs/api/java/lang/reflect/Constructor.html#hashCode()
