大家先体验一下Java的简单性。
1.复制数组
import java.util.Arrays;
/*** 复制数组
* 有一个数组int one长度为5,在使用过程中,数组满了。但还要往one中存数据。
* 要复制数组
*/
public class Test {
public static void main(String[] args) {
int[] one = {1, 2, 3, 4,5};
// Arrays 用于操作数组的工具类
int[] oneCopy = Arrays.copyOf(one, one.length * 2);
for (int temp : oneCopy) {
System.out.println(temp);
}
}
}
public class Test {
public static void main(String[] args){
/**
* 复制数组
* 有一个数组int one长度为5,在使用过程中,数组满了。但还要往one中存数据。
* 要复制数组
*/
int[] one = {1,2,3,4,5};
//先创建一个新数组,长度为one*2
int[] oneCopy = new int[one.length*2];
//得循环旧数组长度,因为新的长度比旧的长,会导致数组越界
for(int i=0;i<one.length;i++){
oneCopy[i] = one[i];
}
//打印
for(int temp:oneCopy){
System.out.println(temp);
}
}
}
下面是用以前学的C的思想写的
2.排序
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] one = {89, 6, 1, 76, 4, 12, 5, 22, 35, 36, 0};
// 在Java中如何排序?
Arrays.sort(one);
for (int temp : one) {
System.out.print(temp + ",");
}
}
}
同样下面用C的写法写一下
//冒泡排序
public class Test {
public static void main(String[] args) {
int[] one = {1,2,4,6,3,5,0};
int n = one.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (one[j] > one[j + 1]) {
int t = one[j];
one[j]=one[j+1];
one[j+1]=t;
}
}
}
for (int i = 0; i < n; i++) {
System.out.print(one[i]+" ");
}
}
}
//插入排序
public class Test {
public static void main(String[] args) {
int[] one = {1,2,4,6,3,5,0};
for (int i = 1; i < one.length; i++) {
int n = one[i];
int j = i - 1;
while (j >= 0 && one[j] > n) {
one[j + 1] = one[j];
j = j - 1;
}
one[j + 1] = n;
}
for (int temp : one) {
System.out.print(temp+" ");
}
}
}
插入数组
import java.util.Arrays;
/**
* 查找元素
*/
public class Test {
public static void main(String[] args) {
int[] one = {1,2,4,6,3,5,0};
// Java中查找元素分为两步:
// 第一步:排序:
Arrays.sort(one);
// 第二步:查找 num是排序后的下标
int num = Arrays.binarySearch(one, 2);
System.out.println("下标是:" + num);
System.out.println(one[num]);
}
}