數組
一、取出一個數組的最大值
使用for()循環遍歷數組
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.快速排序
public static void selectSort(int[] arr)
{
for(int i = 0; i < arr.length - 1; i++)
{
for(int j = i + 1; j < arr.length; j++)
{
if(arr[i] > arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
2.冒泡排序
public static void bubbleSort(int[] arr)
{
for(int i = 0; i < arr.length - 1; i++)
{
for(int j = 0; j < arr.length - i - 1; j++)
{
if(arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
三、二維數組
二維數組的實質就是存儲是一維數組的數組。
1.定義二維數組:
數組類型[][] 數組名 = new 數組類型[一維數組的個數][每一個一維數組中元素的個數];
2.二維數組的初始化方式:
動態初始化:
數據類型[][] 變量名 = new 數據類型[長度1][長度2];
靜態初始化:
數據類型[][] 變量名 = {{元素1,元素2...},{元素1,元素2...},{元素1,元素2...} ..}
示例代碼:
public class Mian {
public static void main(String[] args)
{
int [][] a = new int[][]{ {23,4,5},{2},{4,5,78,56,90} };
printArr2( a );
System.out.println();
System.out.println("累加和是: "+getSum(a) );
System.out.println("統計元素個數: "+getDataCount(a) );
System.out.println("Hello World!");
}
// 定義一個遍歷二維數組的功能函數
public static void printArr( int [][] a ){
for ( int i = 0 ; i < a.length ; i++ )
{
for ( int j = 0 ; j < a[i].length ; j++ )
{
System.out.print( a[i][j]+" ," );
}
}
}
// 定義一個函數計算二維數組中的元素的累加和
public static long getSum( int [][] a ){
long sum = 0L;// 定義一個結果變量
for ( int i = 0 ; i < a.length ; i++ )
{
for ( int j = 0 ; j < a[i].length ; j++ )
{
sum+=a[i][j];
}
}
return sum;
}
// 統計二維數組中元素的個數
public static int getDataCount( int [][] a ){
int count = 0;// 記錄元素個數
for ( int i = 0 ; i < a.length ; i++ )
{
for ( int j = 0 ; j < a[i].length ; j++ )
{
count++;
}
}
return count;
}
}
四、Java8 增強工具類 Arrays
1.binarySearch():
查找數組中爲 key 的 下標 :binarySearch 二分法查找,數組必須有序,且存在此數組中,否則返回負數下標
Arrays.binarySearch(Object[] a,Object key):int
Arrays.binarySearch(Object[] a, int fromIndex, int toIndex,Object key):int
2.copyOf():
copyOf:
複製出新的數組,複製長度由 newLength 決定,長度可大於被複制數組的長度
copyOf(T[] original, int newLength):T[]
copyOfRange:
複製指定下標範圍內的值
copyOfRange(T[] original, int from, int to):T[]
3.sort():
默認進行升序排序,可自定義排序
sort(Object[] a):void
sort(Object[] a, int fromIndex, int toIndex):void
sort(T[] a, Comparator<? super T> c):void
sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c):void
4.toString():
將數組元素轉成String輸出
toString(Object[] a):String
deepToString:
將二維數組元素轉成String輸出
deepToString(Object[] a):String
5.equals():
比較一維數組內容是否相等
equals(Object[] a, Object[] a2)
deepEquals:
比較二維數組內容是否相等
deepEquals(Object[] a1, Object[] a2)
6.fill():
將一個數組全部置爲 val ,或在下標範圍內將數組置爲 val
fill(Object[] a, Object val):void
fill(Object[] a, int fromIndex, int toIndex, Object val):void
7.setAll():
一個數組全部做表達式操作
setAll(T[] array, IntFunction<? extends T> generator):void
8.stream():
將數組轉爲流式,對array進行流式處理,可用一切流式處理的方法
stream(T[] array):Stream<T>