08.自定义工具类

作者: 今天庹 | 来源:发表于2018-09-15 17:21 被阅读0次

自定义工具类

A:需求:自定义一个专门对数组操作的工具类,具有的功能如下

  1. 定义一个方法,该方法可以返回数组中最大元素
  2. 定义一个方法,该方法根据指定的值去数组中查找是否存在该值
    存在,返回该值在数组中的索引
    不存在,返回-1
package com.itheima_03;

public class MyArrays {
    private MyArrays() {}
        
        /*
         * 返回数组中最大的元素
         */
        public static int getMax(int[] arr) {
            int max = 0;//参照物
            //遍历数组
            for(int x = 0; x < arr.length; x++) {
                if(arr[x] > max) {
                    max = arr[x];//替换参照物
                }
            }
            return max;
        }
        
        /*
         * 返回数组中指定参数的索引
         */
        public static int getIndex(int[] arr, int a) {
            for(int x = 0; x < arr.length; x++) {
                if(arr[x] == a) {
                    return x;
                }
            }
            
            return -1;//如果查不到指定的参数,则返回-1
        }
}
package com.itheima_03;

public class MyArray4Demo {
    public static void main(String[] args) {
        int[] arr = {3,5,8,10,1};
        int max = MyArrays.getMax(arr);
        System.out.println(max);
        
        int index = MyArrays.getIndex(arr, 8);
        System.out.println(index);
    }
}

类变量与实例变量辨析

  • A:类变量:其实就是静态变量

    • 定义位置:定义在类中方法外
    • 所在内存区域:方法区
      生命周期:随着类的加载而加载
      特点:无论创建多少对象,类变量仅在方法区中,并且只有一份
  • B:实例变量:其实就是非静态变量

    • 定义位置:定义在类中方法外
    • 所在内存区域:堆
      生命周期:随着对象的创建而加载
      特点:每创建一个对象,堆中的对象中就有一份实例变量

相关文章

网友评论

    本文标题:08.自定义工具类

    本文链接:https://www.haomeiwen.com/subject/tvjagftx.html