The equals() method of java.util.AbstractList class is used to compare the specified object with this list for equality. Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal. (Two elements e1 and e2 are equal if (e1==null ? e2==null : e1.equals(e2)).) In other words, two lists are defined to be equal if they contain the same elements in the same order.
Syntax:
public boolean equals(Object o)
Parameters: This method takes the object o as a parameter to be compared for equality with this list.
Returns Value: This method returns true if the specified object is equal to this list.
Below are the examples to illustrate the equals() method.
Example 1:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
AbstractList<String>
arrlist1 = new ArrayList<String>();
arrlist1.add( "A" );
arrlist1.add( "B" );
arrlist1.add( "C" );
arrlist1.add( "D" );
arrlist1.add( "E" );
System.out.println( "First ArrayListlist : "
+ arrlist1);
AbstractList<String>
arrlist2 = new ArrayList<String>();
arrlist2.add( "A" );
arrlist2.add( "B" );
arrlist2.add( "C" );
arrlist2.add( "D" );
arrlist2.add( "E" );
System.out.println( "Second ArrayList : "
+ arrlist2);
boolean value = arrlist1.equals(arrlist2);
System.out.println( "Are both list equal : "
+ value);
}
catch (NullPointerException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
First ArrayListlist : [A, B, C, D, E]
Second ArrayList : [A, B, C, D, E]
Are both list equal : true
Example 2:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
AbstractList<Integer>
arrlist1 = new ArrayList<Integer>();
arrlist1.add( 10 );
arrlist1.add( 20 );
arrlist1.add( 30 );
arrlist1.add( 40 );
arrlist1.add( 50 );
System.out.println( "First ArrayListlist : "
+ arrlist1);
AbstractList<Integer>
arrlist2 = new ArrayList<Integer>();
arrlist2.add( 10 );
arrlist2.add( 20 );
arrlist2.add( 30 );
System.out.println( "Second ArrayList : "
+ arrlist2);
boolean value = arrlist1.equals(arrlist2);
System.out.println( "Are both list equal : "
+ value);
}
catch (NullPointerException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
First ArrayListlist : [10, 20, 30, 40, 50]
Second ArrayList : [10, 20, 30]
Are both list equal : false