思路1
- 对数组中的元素进行遍历,然后用每一个元素与需要查询的值进行比较即可
- 代码实现:
public class Test1 {
public static void main(String[] args) {
boolean flag=false;
int[] array = {1, 2, 3, 4, 6};
for (int i:array){
if (i==7){
flag=true;
}
}
if (flag==true){
System.out.println("数组中含有这个元素!");
}else {
System.out.println("数组中没有这个元素!");
}
}
}
思路2
- 我们知道集合相当于可以动态扩容的数组,而且集合中的类含有contains方法可以验证是否含有某个元素。所以我们先考虑把数组存储在集合中。
- 代码实现:
public class Test2 {
public static void main(String[] args) {
Integer [] array = {1, 2, 3, 4, 6};
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(array));
boolean contains = list.contains(3);
if (contains==true){
System.out.println("数组中含有这个元素!");
}else {
System.out.println("数组中没有这个元素!");
}
}
}
思路3
- 使用Set集合中的HashSet,HashSet集合实际上是用HashMap实现的,数组转换为集合后,会存储在键中,且没有重复元素。
- 代码实现:
public class Test3 {
public static void main(String[] args) {
Integer [] array = {1, 2, 3, 4, 6};
HashSet<Integer> set = new HashSet<>(Arrays.asList(array));
if (set.contains(6)){
System.out.println("数组中含有该元素!");
}else {
System.out.println("数组中没有该元素!");
}
}
}
总结
- 三种方式均能够实现查找数组中某个元素的功能,但是效率是不一样的,for循环的效率最高,因为它不需要创建出集合,而另外两个要在创建完集合后才能进行查找。