在Java中,Set是一个不允许重复元素的集合。高效查找的方法取决于Set的实现类型。以下是两种常用的Set实现及其高效的查找方法:
示例代码:
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
set.add(3);
int target = 2;
if (set.contains(target)) {
System.out.println("Target " + target + " found in the set.");
} else {
System.out.println("Target " + target + " not found in the set.");
}
}
}
示例代码:
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<Integer> set = new TreeSet<>();
set.add(1);
set.add(2);
set.add(3);
int target = 2;
if (set.contains(target)) {
System.out.println("Target " + target + " found in the set.");
} else {
System.out.println("Target " + target + " not found in the set.");
}
}
}
总结:
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
相关推荐:java中set如何高效去重