java 中 针对数组进行的工具类
? ? ? ?1.遍歷數組的方法: ?
? ? ? ? ? ? ? public static void printfArray(int[] arr)
?2. 獲取數組中最大值:
? ? ? ? ? ? ? public static int getMax(int[] arr)
? ? ? ?
public class ArrayTool {
//把構造方法私有,外界就不能在創建對象了
/**
* 這是私有構造
*/
private ArrayTool(){}
/**
* 這是遍歷數組的方法,遍歷后的格式是:[元素1, 元素2, 元素3, ...]
* @param arr 這是要被遍歷的數組
*/
public static void printArray(int[] arr) {
System.out.print("[");
for(int x=0; x<arr.length; x++) {
if(x == arr.length-1) {
System.out.println(arr[x]+"]");
}else {
System.out.print(arr[x]+", ");
}
}
}
/**
* 這是獲取數組中最大值的方法
* @param arr 這是要獲取最大值的數組
* @return 返回數組中的最大值
*/
public static int getMax(int[] arr) {
int max = arr[0];
for(int x=1; x<arr.length; x++) {
if(arr[x] > max) {
max = arr[x];
}
}
return max;
}
/**
* 獲取指定元素在數組中第一次出現的索引,如果元素不存在,就返回-1
* @param arr 被查找的數組
* @param value 要查找的元素
* @return 返回元素在數組中的索引,如果不存在,返回-1
*/
public static int getIndex(int[] arr,int value) {
int index = -1;
for(int x=0; x<arr.length; x++) {
if(arr[x] == value) {
index = x;
break;
}
}
return index;
}
}
轉載于:https://www.cnblogs.com/panda88/p/5962386.html
總結
以上是生活随笔為你收集整理的java 中 针对数组进行的工具类的全部內容,希望文章能夠幫你解決所遇到的問題。