这是我参与2022首次更文挑战的第14天,活动详情查看:2022首次更文挑战
Java程序设计 System类、对象克隆、Math类、Random随机数
System类
System是一个系统类,其最主要的功能是进行信息的打印输出
常用方法
| 方法 | 作用 |
|---|---|
| public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length) | 数组复制操作 |
| public static long currentTimeMillis() | 取得当前的日期时间,以long 数据返回 |
| public static void gc() | 执行GC执行 |
数组复制
public class Hello {
public static void main(String[] args) {
String s[] = {"h","e","e"};
String[] s2= new String[2];
System.arraycopy(s,0,s2,0,2);
for(String i : s2){
System.out.print(i+" ");
}
}
}
统计花费时间
public class Hello {
public static void main(String[] args) {
long a=System.currentTimeMillis();
for(int i=0;i<=500000;i++);
long b=System.currentTimeMillis();
System.out.println("花费时间"+(b-a)+"ms");
}
}
对象克隆
Object类中提供的clone()方法
利用已有的对象克隆出一个成员属性内容完全相同的实例化对象
克隆方法:
protected Object clong() throws CloneNotSupportedException
Math类演示:
public class Hello {
public static void main(String[] args) throws Exception {
M a=new M("A");
M b=(M) a.clone();
b.setS("B");
System.out.println(a);
System.out.println(b);
}
}
class M implements Cloneable{
private String s;
public M(String s){
this.s=s;
}
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
@Override
public String toString() {
return "M{" +
"s='" + s + '\'' +
'}';
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
对象的克隆操作可以通过Object类提供的clone()方法来完成,由于此方法在Object中使用protected设置了访问权限,所以该方法只能通过子类来进行调用,而对象克隆成功后就会利用已有的对象构建一个全新的对象,彼此之间的操作不会有任何影响。
Math类
能够进行常规的数学计算处理,例如,四舍五入、三角函数、乘方处理等。
public class Hello {
public static void main(String[] args) throws Exception{
System.out.println("最大值:"+Math.max(15,50));
System.out.println("最小值:"+Math.min(12,10));
System.out.println("绝对值:"+Math.abs(-12));
System.out.println("对数:"+Math.log(6));
System.out.println("四舍五入:"+Math.round(123.5));
System.out.println("四舍五入:"+Math.round(-123.5));
System.out.println("乘方:"+Math.pow(4,5));
}
}
Random随机数
生成随机数
利用Random随机生成了10个不大于10的正整数
import java.util.Random;
public class Hello {
public static void main(String[] args) {
Random a=new Random();
for(int x=0;x<10;x++){
System.out.print(a.nextInt(10)+" ");
}
}
}