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
WBOYforward
2023-05-22 10:03:251329browse

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;
}

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;
}

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete