Java Constructor equals()方法及示例
java.lang.reflect.Constructor 的 equals() 方法用于比较这个Constructor和传递的对象。如果对象相同,则该方法返回真。在java中,两个构造函数对象是相同的,当且仅当它们由同一个类声明并且具有相同的形式参数类型。
语法
public boolean equals(Object obj)
参数: 该方法接受 obj ,它是要与之比较的参考对象。
返回 :如果该对象与obj参数相同,该方法返回 true 。否则,它返回false。
以下程序说明了equals()方法:
程序1 :
// Java program to illustrate equals() 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();
// apply equals method
System.out.println("Constructor 1: " + cons[0]);
System.out.println("Constructor 2: " + cons[1]);
boolean result = cons[0].equals(cons[1]);
// print result
System.out.println("Both constructor are equal: "
+ result);
}
}
输出。
Constructor 1: public java.lang.String(byte[], int, int)
Constructor 2: public java.lang.String(byte[], java.nio.charset.Charset)
Both constructor are equal: false
程序2
// Java program to illustrate equals() 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();
// apply equals method
System.out.println("Constructor 1: " + cons[0]);
Object obj = cons[0];
System.out.println("Object: " + obj);
boolean result = cons[0].equals(obj);
// print result
System.out.println("Both constructor are equal: "
+ result);
}
}
输出。
Constructor 1: public java.util.ArrayList(java.util.Collection)
Object: public java.util.ArrayList(java.util.Collection)
Both constructor are equal: true
参考资料: https://docs.oracle.com/javase/10/docs/api/java/lang/reflect/Constructor.html#equals(java.lang.Object)