Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

java - Why are two empty ArrayLists with different generic types equal?

I have a doubt regarding how equals() method works for ArrayList. The below code snippet prints true.

ArrayList<String> s = new ArrayList<String>();
ArrayList<Integer> s1 = new ArrayList<Integer>();
System.out.println(s1.equals(s));

Why does it print true?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Look the doc for the equals() method of ArrayList

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.

Since there are no elements, all the conditions satisfied and hence true.

If you add elements to the both list (atleast one in each), to see the desired output.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...