Constructor equals() method in Java with Examples
Last Updated :
29 Oct, 2019
The constructor class provides information about a single constructor for a class and it also provides access to that constructor.
The equals() method of java.lang.reflect.Constructor is used to compare this Constructor against the passed object. If the objects are the same then the method returns true. In java Two Constructor objects are the same if and only if they were declared by the same class and have the same formal parameter types.
Syntax:
public boolean equals(Object obj)
Parameters: This method accepts obj which is the reference object with which to compare.
Return: This method returns true if this object is the same as the obj argument. Else it returns false.
Below programs illustrate equals() method:
Program 1:
import java.lang.reflect.Constructor;
public class GFG {
public static void main(String[] args)
{
Class classObj = String. class ;
Constructor[] cons = classObj.getConstructors();
System.out.println( "Constructor 1: " + cons[ 0 ]);
System.out.println( "Constructor 2: " + cons[ 1 ]);
boolean result = cons[ 0 ].equals(cons[ 1 ]);
System.out.println( "Both constructor are equal: "
+ result);
}
}
|
Output:
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
Program 2:
import java.lang.reflect.Constructor;
import java.util.ArrayList;
public class GFG {
public static void main(String[] args)
{
Class classObj = ArrayList. class ;
Constructor[] cons = classObj.getConstructors();
System.out.println( "Constructor 1: " + cons[ 0 ]);
Object obj = cons[ 0 ];
System.out.println( "Object: " + obj);
boolean result = cons[ 0 ].equals(obj);
System.out.println( "Both constructor are equal: "
+ result);
}
}
|
Output:
Constructor 1: public java.util.ArrayList(java.util.Collection)
Object: public java.util.ArrayList(java.util.Collection)
Both constructor are equal: true
References: https://docs.oracle.com/javase/10/docs/api/java/lang/reflect/Constructor.html#equals(java.lang.Object)
Share your thoughts in the comments
Please Login to comment...