查询问题

【1】查询指定位置的元素

 1 public class TestArray05 {
 2     //这是一个main方法,程序的入口
 3     public static void main(String[] args) {
 4         //查询指定位置的元素
 5         //给定一个数组:
 6         int [] arr = {12,34,567,3,10};
 7         //查找索引为2的位置上对应的元素是什么
 8         System.out.println(arr[2]);
 9     }
10 }

上面代码体现了数组的一个优点

在按照位置元素的时候,直接一步到位,效率非常高

【2】查询指定元素的位置---》找到元素对应的索引

 1 public class TestArray06 {
 2     //这是一个main方法,程序的入口
 3     public static void main(String[] args) {
 4         //查询指定元素的位置--》找出元素对应的索引
 5         //给定一个数组:
 6         int [] arr = {12,34,56,7,3,10};
 7         //             0  1  2 3  4 5
 8 
 9         //功能:查询元素56对应的索引
10         //调用方法
11         int index= getIndex(arr,44);
12         //后续对index的值进行判断
13         if(index!=-1){
14             System.out.println("元素对应的索引:"+index);
15         }else{//index==-1
16             System.out.println("查无此数");
17         }
18     }
19     /*
20     * 定义一个方法:查询数组定义的元素对应的索引:
21     * 不确定因素:那个数组,那个指定元素   (形参)
22     * 返回值:索引
23     * */
24     public static int getIndex(int [] arr,int ele){
25         int index = -1;//这个初始值只要不是数组的索引即可
26         for (int i = 0; i < arr.length; i++) {
27             if(arr[i]==ele){
28                 index = i;//只要找到了元素,那么index就变成为i
29                 break;//只要找到这个元素,循坏就停止
30             }
31         }
32         return index;
33     }
34 }

【3】将查指定元素对应的索引的功能提取为方法

 1 public class TestArray06 {
 2     //这是一个main方法,程序的入口
 3     public static void main(String[] args) {
 4         //查询指定元素的位置--》找出元素对应的索引
 5         //给定一个数组:
 6         int [] arr = {12,34,56,7,3,10};
 7         //             0  1  2 3  4 5
 8 
 9         //功能:查询元素56对应的索引
10         //调用方法
11         int index= getIndex(arr,34);
12         //后续对index的值进行判断
13         if(index!=-1){
14             System.out.println("元素对应的索引:"+index);
15         }else{//index==-1
16             System.out.println("查无此数");
17         }
18     }
19     /*
20     * 定义一个方法:查询数组定义的元素对应的索引:
21     * 不确定因素:那个数组,那个指定元素   (形参)
22     * 返回值:索引
23     * */
24     public static int getIndex(int [] arr,int ele){
25         int index = -1;//这个初始值只要不是数组的索引即可
26         for (int i = 0; i < arr.length; i++) {
27             if(arr[i]==ele){
28                 index = i;//只要找到了元素,那么index就变成为i
29                 break;//只要找到这个元素,循坏就停止
30             }
31         }
32         return index;
33     }
34 }

 

内存分析

 

posted @ 2021-08-11 16:47  再努力一些  阅读(76)  评论(0)    收藏  举报