1. 程式人生 > 其它 >執行java例項5

執行java例項5

1.陣列獲取最大和最小值
import java.util.Arrays;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
Integer[] numbers = { 8, 2, 7, 1, 4, 9, 5};
int min = (int) Collections.min(Arrays.asList(numbers));//獲取最小值
int max = (int) Collections.max(Arrays.asList(numbers));//獲取最大值
System.out.println("最小值: " + min);
System.out.println("最大值: " + max);
}
}
2.數組合並
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String args[]) {
String a[] = { "A", "E", "I" };
String b[] = { "O", "U" };
List list = new ArrayList(Arrays.asList(a));
list.addAll(Arrays.asList(b));
Object[] c = list.toArray();
System.out.println(Arrays.toString(c));//{"A","E","I","O","U"}
}
3.陣列填充
import java.util.*;

public class FillTest {
public static void main(String args[]) {
int array[] = new int[6];
Arrays.fill(array, 100);
for (int i=0, n=array.length; i < n; i++) {
System.out.println(array[i]);//100 100 100 100 100 100
}
System.out.println();
Arrays.fill(array, 3, 6, 50);
for (int i=0, n=array.length; i< n; i++) {
System.out.println(array[i]);//100 100 100 50 50 50
}
}
}
4.陣列擴容
public class Main {
public static void main(String[] args) {
String[] names = new String[] { "A", "B", "C" };
String[] extended = new String[5];
extended[3] = "D";
extended[4] = "E";
System.arraycopy(names, 0, extended, 0, names.length);
for (String str : extended){
System.out.println(str);
}
}
}
5.查詢陣列中的重複元素
public class MainClass {
public static void main(String[] args)
{
int[] my_array = {1, 2, 5, 5, 6, 6, 7, 2, 9, 2};
findDupicateInArray(my_array);

}

public static void findDupicateInArray(int[] a) {
    int count=0;
    for(int j=0;j<a.length;j++) {
        for(int k =j+1;k<a.length;k++) {
            if(a[j]==a[k]) {
                count++;
            }
        }
        if(count==1)
           System.out.println( "重複元素 : " +  a[j] );
        count = 0;
    }
}

}