在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.");
}
}
}
总结: