文章目录
定时调度
- 定时调度
- Array类
- 数组排序Arrays.sort
- Arrays.compare比较大小
- 数组二分查找法(自己写)
- Arrays.binarySearch
import java.util.Timer;
import java.util.TimerTask;
class TaskThread extends TimerTask { // 实现定时任务
@Override
public void run() { // 所有的定时任务都通过线程描述
System.out.println("【定时任务】沐言优拓:www.yootk.com");
}
}
public class YootkDemo { // 李兴华编程训练营:yootk.ke.qq.com
public static void main(String[] args) throws Exception {
Timer timer = new Timer() ; // 调度类
// 1秒之后开始调度,执行1次,每2秒重复调用一次
timer.schedule(new TaskThread(), 1000, 2000);
}
}
Array类
数组排序Arrays.sort
public class YootkDemo { // 李兴华编程训练营:yootk.ke.qq.com
public static void main(String[] args) throws Exception {
int data[] = new int[]{1, 5, 7, 2, 90, 23, 56, 78};
System.out.println("【原始数组内容】" + Arrays.toString(data));
Arrays.sort(data); // 数组排序
System.out.println("【排序后的数组】" + Arrays.toString(data));
}
}
Arrays.compare比较大小
import java.util.Arrays;
public class YootkDemo { // 李兴华编程训练营:yootk.ke.qq.com
public static void main(String[] args) throws Exception {
int dataA[] = new int[]{1, 7, 5};
int dataB[] = new int[]{5, 7, 1};
System.out.println("【相等判断 - 未排序】" + Arrays.equals(dataA, dataB));
Arrays.sort(dataA);
Arrays.sort(dataB);
System.out.println("【相等判断 - 已排序】" + Arrays.equals(dataA, dataB));
System.out.println("【大小关系判断】" + Arrays.compare(new int[]{2, 8, 9}, dataA));
}
}
数组二分查找法(自己写)
import java.util.Arrays;
public class YootkDemo { // 李兴华编程训练营:yootk.ke.qq.com
public static void main(String[] args) throws Exception {
int data[] = new int[]{3, 10, 5, 9, 1, 7};
System.out.println("【原始数组】" + Arrays.toString(data));
int key = 9 ; // 查找的关键数据
Arrays.sort(data);
System.out.println("【排序数组】" + Arrays.toString(data));
System.out.println("【数据查询】" + search(data, key));
}
/**
* 本方法的主要作用是查找在指定的数组之中是否存在有指定的数据内容
* 如果存在则返回相应的索引,如果不存在返回负数
* @param data 要查找的数组内容
* @param key 要查找的数据
* @return 数组索引,如果没有找到返回负数
*/
public static int search(int data[], int key) {
int low = 0; // 开始索引,数组的首个元素索引
int high = data.length - 1; // 结束索引,数组结尾的索引
// 现代的语言设计过程之中,强调通过循环结构来代替递归结果,这样可以提升处理性能
while (low >> 1; // 进行中间索引的确定,折半
int midVal = data[mid]; // 获取中间值数据
if (midVal key) { // 判断中间值是否大于要查找的内容
high = mid - 1; // 不再判断后面,而是修改high
} else { // 数据匹配成功
return mid; // 返回当前索引
}
}
return -(low + 1); // 负数,没有查询到
}
}
Arrays.binarySearch
注意,查找之前要先排序Arrays.sort
import java.util.Arrays;
public class YootkDemo { // 李兴华编程训练营:yootk.ke.qq.com
public static void main(String[] args) throws Exception {
int data[] = new int[]{3, 10, 5, 9, 1, 7};
System.out.println("【原始数组】" + Arrays.toString(data));
int key = 9 ; // 查找的关键数据
Arrays.sort(data);
System.out.println("【排序数组】" + Arrays.toString(data));
System.out.println("【数据查询】" + Arrays.binarySearch(data, key));
}
}