自定义数组操作工具类代码示例
生活随笔
收集整理的這篇文章主要介紹了
自定义数组操作工具类代码示例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
自定義一個操作數據的工具類,其實工具類的編寫很簡單,將方法靜態化,將構造方法私有化就可以了。
工具類代碼:
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}}測試工具類:
@Testpublic void testMyArrays(){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);}總結
以上是生活随笔為你收集整理的自定义数组操作工具类代码示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Math工具类常用API使用案例
- 下一篇: 类变量与实例变量辨析