Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the problem that the distinct () method in Hashcode does not work.

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "how to solve the problem that the distinct () method in Hashcode does not work". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

The doubt of the boss

The boss wrote a piece of code like this in the project:

List list = new ArrayList (); / / omit the add data operation List models = list.stream (). Map (ProjectId::getDeviceModel). Distinct (). Collect (Collectors.toList ()); System.out.println (models)

As a result, the distinct () method in this code didn't work and didn't live up to expectations.

There is no problem through the API document, so the boss opened the debug mode and found that it was strange that the equals methods of the entity class did not enter.

Solution idea

According to part of the code and implementation ideas sent by the boss, the whole simulated test program is complete, creating two entity classes ProjectId and DeviceModel, and rewriting the equals method (communicating with the boss, he rewrote the equals method, and using it alone is effective).

The DeviceModel entity class, which simply overrides the equals method, only compares whether the field no is equal.

@ Data public class DeviceModel {private String no; @ Override public String toString () {return no;} @ Override public boolean equals (Object other) {if (this = = other) {return true;} if (other = = null | | getClass ()! = other.getClass ()) {return false } return this.toString () .equals (other.toString ());}}

ProjectId entity class, overriding the equals method

@ Data public class ProjectId {private int id; private DeviceModel deviceModel;}

Then, the test class is built:

Public class Test {public static void main (String [] args) {List list = new ArrayList (); DeviceModel device1 = new DeviceModel (); device1.setNo ("1"); ProjectId projectId1 = new ProjectId (); projectId1.setDeviceModel (device1); projectId1.setId (1); list.add (projectId1); DeviceModel device2 = new DeviceModel (); device2.setNo ("1") ProjectId projectId2 = new ProjectId (); projectId2.setDeviceModel (device2); projectId2.setId (1); list.add (projectId2); DeviceModel device3 = new DeviceModel (); device3.setNo ("2"); ProjectId projectId3 = new ProjectId (); projectId3.setDeviceModel (device3); projectId3.setId (2); list.add (projectId3) List models = list.stream (). Map (ProjectId::getDeviceModel). Distinct (). Collect (Collectors.toList ()); System.out.println (models);}}

First build a set of data, and then let device1 override the equals method like the no property of device2, which in theory should be equal, and the device3 object is used as a contrast.

Execute the above program, and the console prints as follows:

[1, 1, 2]

Indeed restore the boss's bug, but also wonder why this is the case. But now that bug has reappeared, the solution is relatively simple.

At this point, the boss sent another clue that it was all right in the form of a for loop:

List results = new ArrayList (); for (DeviceModel deviceModel: list.stream (). Map (ProjectId::getDeviceModel) .requests (Collectors.toList ()) {if (! results.contains (deviceModel)) {results.add (deviceModel);}} System.out.println (results)

This form of implementation can also be used as a contrast.

Problem troubleshooting

Debug is the first thing that comes to mind when troubleshooting problems, but it is also the case that the equals method is not used.

A closer look at the code shows that the map operation is used in the Stream processing. As mentioned in previous articles, to determine whether an object already exists in Map is to locate the corresponding array subscript by the hash value of key, and save it directly if the Entry at that location has no value; if there is already an existing value, compare whether the value is the same by the equals method.

So, is it because you rewrote the equals method instead of the hashcode method? Therefore, the hashcode method is added to the DeviceModel class:

@ Override public int hashCode () {/ / JDK7's new Objects utility class return Objects.hash (no);}

Execute it again, test the method, and find that it can be removed successfully. Obviously, the boss's mistake was that he violated a principle when rewriting equals methods: if the equals methods of a class are equal, then their hashcode methods must be equal. This principle is violated because the hashcode method is not overridden. As a result, there is an inexplicable problem when using Map implicitly.

Follow up

After all these twists and turns, the problem was finally solved. You must have a better understanding of why you have to rewrite the equals method when you rewrite the hashcode method. Later, the boss asked me another question: why does the list.contains method not have this problem?

Because the underlying structure of List is an array, unlike Map, Key is not compared with hash processing in order to improve efficiency. Take a brief look at the core implementation of the contains method in ArrayList:

Public int indexOf (Object o) {if (o = = null) {for (int I = 0; I < size; data +) if (elementdata [I] = = null) return I;} else {for (int I = 0; I < size; idata +) if (o.equals (elementdata [I])) return I;} return-1;}

You can see that if the object is not null, it is handled by the equals method called in a loop.

This is the end of the content of "how to solve the problem that the distinct () method in Hashcode does not work". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report