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 java uses HashSet to determine whether a primary key exists

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article is about how java uses HashSet to determine whether a primary key exists. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Use HashSet to determine whether the primary key exists

HashSet implements the Set interface, which is supported by a hash table (actually HashMap), but does not guarantee the iterative order of set and allows the use of null elements. The time complexity of HashSet is the same as that of HashMap. If there is no hash conflict, the time complexity is O (1). If there is a hash conflict, the time complexity is not more than O (n). Therefore, in daily coding, you can use HashSet to determine whether the primary key exists.

Example: given a string (not necessarily all letters), return the first recurring character.

/ * * find the first repeating character * / public static Character findFirstRepeatedChar (String string) {/ / check the empty string if (Objects.isNull (string) | | string.isEmpty ()) {return null;} / / find the repeating character char [] charArray = string.toCharArray (); Set charSet = new HashSet (charArray.length) For (char ch: charArray) {if (charSet.contains (ch)) {return ch;} charSet.add (ch);} / / empty return null;} is returned by default

Here, because the add function of Set has a feature-if the added element already exists in the collection, it will return false. You can simplify the code to:

If (! charSet.add (ch)) {return ch;} Thank you for reading! This is the end of the article on "how java uses HashSet to determine whether the primary key exists". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!

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