Why doesn't my peer method work?

I use ArrayList , and at some point in the program, I use the contains method to check for the presence of a specific element in an ArrayList . An ArrayList stores objects of type CharProfile , a custom class, and it sees that it contains char.

So I use the equals method in the contains method. So something like CharProfile.contains(char) , but it does not work.

I override the equals method in CharProfile:

 @Override public boolean equals(Object o) { if (this.character == (Character)o) { return true; } else { return false; } } 

So, it should use my equals method when CharProfile tries to use it, right? So why doesn't it work?

(In terms of β€œnot working,” I mean the fact that contains always returns false.)

+4
source share
5 answers

You are comparing a reference type using ==, which is not true. You must use equals , with null -checks added.

But this is only the beginning. The main problem is that you are trying to compare a CharProfile object with a Character object. You probably need this:

 public boolean equals(Object o) { return o instanceof CharProfile && this.character.equals((CharProfile)o).character; } 

This assumes your Character field is never null. If it can be null, you need to check it before dereferencing.

+9
source

You exceed equal values ​​to check for link equality, the default behavior of the == operator

+2
source

You need to use equals (). You can also make it oneliner and be more explicit in your casting.

 @Override public boolean equals(Object o) { return o instanceof Character && this.character.equals(Character.class.cast(o)); } 
+1
source

You must use the equals () method and DO NOT forget to override the hashCode () method. They go hand in hand.

Some people do not know this, but if you use eclipse, you can right-click, select Source-> and Generate hashCode () and equals () ...

But I suggest that you first find out what they are for before using this convenience.

+1
source

For example, you have a CharProfile as shown below.

 List<CharProfile> list = new ArrayList<CharProfile>(); list.add(new CharProfile('a')); list.add(new CharProfile('b')); list.add(new CharProfile('c')); 

When list.contains('a') is is, the JVM will not call the Override equals() CharProfile .

More clearly:

 public class Data { public boolean equals(Object o) { System.out.println("I am data"); return false; } } 

When list.contains(new Data()) works, the JVM will not call the Override equals() Data method. Now you will receive a message as I am data. .

0
source

Source: https://habr.com/ru/post/1442740/


All Articles