Home > Java > javaTutorial > How to use HashSet in java to determine whether the primary key exists

How to use HashSet in java to determine whether the primary key exists

WBOY
Release: 2023-05-22 10:03:25
forward
1330 people have browsed it

Use HashSet to determine whether the primary key exists

HashSet implements the Set interface and is supported by a hash table (actually a HashMap), but does not guarantee the iteration order of the 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 does not exceed O(n). Therefore, in daily coding, you can use HashSet to determine whether the primary key exists.

Case: Given a string (not necessarily all letters), please return the first recurring character.

/** 查找第一个重复字符 */public static Character findFirstRepeatedChar(String string) {    // 检查空字符串
    if (Objects.isNull(string) || string.isEmpty()) {        return null;
    }    // 查找重复字符
    char[] charArray = string.toCharArray();
    Set charSet = new HashSet<>(charArray.length);    for (char ch : charArray) {        if (charSet.contains(ch)) {            return ch;
        }
        charSet.add(ch);
    }    // 默认返回为空
    return null;
}
Copy after login

Among them, because the add function of Set has a characteristic-if the added element already exists in the set, it will return false. The code can be simplified as:

if (!charSet.add(ch)) {    return ch;
}
Copy after login

The above is the detailed content of How to use HashSet in java to determine whether the primary key exists. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template