[Java基础]4. Java常用类

[Java基础]4. Java常用类

一、System类

System类代表当前Java程序的运行平台,程序不能创建System类的对象, System类提供了一些类变量和类方法,允许直接通过System类来调用这些类变量和类方法。

下面方法的修饰符都是static

方法 返回值 说明
currentTimeMillis() long 返回以毫秒为单位的当前时间。
exit(int status) void 终止当前正在运行的 Java 虚拟机。
gc() void 运行垃圾回收器。
getenv() Map 返回一个不能修改的当前系统环境的字符串映射视图。
getenv(String name) String 获取指定的环境变量值。
getProperties() Properties 确定当前的系统属性。
getProperty(String key) String 获取指定键指示的系统属性。
getProperty(String key, String def) String 获取用指定键描述的系统属性。
identityHashCode(Object x) int 返回给定对象的哈希码,该代码与默认的方法 hashCode()
返回的代码一样,无论给定对象的类是否重写 hashCode()。
nanoTime() long 返回最准确的可用系统计时器的当前值,以毫微秒为单位。
import java.util.Map;
import java.util.Scanner;
public class SystemClassDemo {
	public static void main(String[] args) throws Exception {
		// System.in代表标准输入,就是键盘输入
		// Scanner 一般用于获取控制台输入
		Scanner sc = new Scanner(System.in);
		// 判断是否还有下一个输入项
		while (sc.hasNext()) {
			// System.out 标准输出
			String str = sc.next();
			System.out.println("键盘输入的内容是:" + str);
			if (str.endsWith("<#0>")) {
				break;
			}
		}
		// 获取系统所有的环境变量
		System.out.println("‐‐‐‐系统所有的环境变量‐‐‐‐‐‐‐‐");
		Map<String, String> envMap = System.getenv();
		for (String name : envMap.keySet()) {
			System.out.println(name + " ‐‐‐> " + envMap.get(name));
		}
		// System.out
		System.out.println("‐‐‐‐获取指定的系统变量 JAVA_HOME‐‐‐‐‐‐‐‐");
		System.out.println(System.getenv("JAVA_HOME"));
		//获取系统属性
		System.out.println("‐‐‐‐‐getProperties‐‐‐‐");
		System.out.println(System.getProperties());
		System.out.println("‐‐‐‐‐getProperty‐‐‐‐");
		System.out.println(System.getProperty("user.name"));
		// System.gc();
		// gc() 函数的作用只是提醒虚拟机:希望进行一次垃圾回收。
		// 但是它不能保证垃圾回收一定会进行,而且具体什么时候进行是取决于具体的虚拟机的,不System.gc();
		System.out.println("‐‐‐‐currentTimeMillis和nanoTime‐‐‐‐");
		// 返回当前时间与UTC 1970年1月1日午夜的时间差
		// currentTimeMillis 毫秒为单位 1毫秒(ms)=1000000纳秒(ns)
		// nanoTime 纳秒为单位,部分操作系统不支持使用纳秒作为计时单位。
		System.out.println(System.currentTimeMillis());
		System.out.println(System.nanoTime());
		for (int i = 0; i < 10; i++) {
			System.out.println(System.currentTimeMillis() + "<>" + System.nanoTime());
		}
		System.out.println("‐‐‐‐identityHashCode‐‐‐‐");
		// identityHashCode 返回指定对象的精确hashCode值,
		// 下面程序中str1和str2是两个不同对象
		String str1 = new String("Hello,World");
		String str2 = new String("Hello,World");
		// String重写了hashCode()方法——改为根据字符序列计算hashCode值,
		// 因为str1和str2的字符序列相同,所以它们的hashCode方法返回值相同
		System.out.println(str1.hashCode() + "\t" + str2.hashCode());
		// str1和str2是不同的字符串对象,所以它们的identityHashCode值不同
		System.out.println(System.identityHashCode(str1) + "\t" + System.identityHashCode(str2));
		String str3 = "Java";
		String str4 = "Java";
		// str3和str4是相同的字符串对象,所以它们的identityHashCode值相同
		System.out.println(System.identityHashCode(str3) + "\t" + System.identityHashCode(str4));
		//exit 停止正在运行的虚拟机,退出程序
		System.exit(0);
		System.out.println("这一句将不会打印出来,因为没有执行");
	}
}

二、Runtime类

Runtime类代表Java程序的运行时环境,可以访问JVM的相关信息,每个Java程序都有一个与之对应的Runtime实例,应用程序通过该对象与其运行时环境相连。应用程序不能创建自己的Runtime实例,但可以通过getRuntime()方法获取与之关联的Runtime对象。

  • Runtime类是饿汉式单例类:

    public class Runtime{
    	private static Runtime currentRuntime = new Runtime();
    	public static Runtime getRuntime(){
    		return currentRuntime;
    	}
    	private Runtime(){}
    
方法 返回值 修饰符 说明
getRuntime() Runtime static 返回与当前 Java 应用程序相关的运行时对象。
availableProcessors() int 向 Java 虚拟机返回可用处理器的数目。
totalMemory() long 返回 Java 虚拟机中的内存总量。
freeMemory() long 返回 Java 虚拟机中的空闲内存量。
maxMemory() long 返回 Java 虚拟机试图使用的最大内存量。
exec(String command) Process 在单独的进程中执行指定的字符串命令。
gc() void 运行垃圾回收器。
exit(int status) void 通过启动虚拟机的关闭序列,终止当前正在运行的 Java 虚拟机。
halt(int status) void 强行终止目前正在运行的 Java 虚拟机。
import java.io.IOException;
public class RuntimeClassDemo {
public static void main(String[] args) {
	// 获取Java程序关联的运行时对象
	Runtime rt = Runtime.getRuntime();
	System.out.println("处理器数量:" + rt.availableProcessors());
	System.out.println("JVM空闲内存数:" + rt.freeMemory() / 1024 / 1024);
	System.out.println("JVM总内存数:" + rt.totalMemory() / 1024 / 1024);
	System.out.println("JVM试图使用的最大内存:" + rt.maxMemory() / 1024 / 1024);
	//运行外部程序
	try {
		rt.exec("notepad.exe");
	} catch (IOException e) {
		// TODO Auto‐generated catch block
		e.printStackTrace();
	}
	//运行垃圾回收
	//System.gc()内部也使用这个方法 Runtime.getRuntime().gc();
	rt.gc();
	//退出
	// rt.exit(0);
	rt.halt(0);//强制退出
	System.out.println("exit");
	}
}

三、String类

String类常用构造器:

构造器 说明
String(byte[] bytes) 使用平台的默认字符集解码指定的 byte 数组,构造一个新的 String。
String(byte[] bytes, Charset charset)
String(byte[] bytes, int offset, int length)
String(char[] value) 分配一个新的 String,使其表示字符数组参数中当前包含的字符序列。
String(String original) 新创建的字符串是该参数字符串的副本。

String常用判断方法:

下面方法返回值类型都是boolean。

方法名 说明
equals(Object obj) 比较字符串的内容是否相同,区分大小写
equalsIgnoreCase(String str) 比较字符串的内容是否相同,忽略大小写
contains(String str) 判断大字符串中是否包含小字符串
startsWith(String str) 判断字符串是否以某个指定的字符串开头
endsWith(String str) 判断字符串是否以某个指定的字符串结尾
isEmpty() 判断字符串是否为空。

String类常用的获取方法:

方法名 返回值 说明
length() int 获取字符串的长度。
charAt(int index) char 获取指定索引位置的字符
indexOf(int ch) int 返回指定字符在此字符串中第一次出现处的索引。
indexOf(int ch,int fromIndex) int 从指定的索引开始搜索。
indexOf(String str) int 指定子字符串
indexOf(String str,int fromIndex) int 指定子字符串, 指定索引
lastIndexOf(int ch) int 返回指定字符在此字符串中最后一次出现处的索引。
lastIndexOf(int ch,int fromIndex) int 从指定的索引处开始进行反向搜索。
lastIndexOf(String str) int 子字符串
lastIndexOf(String str,int fromIndex) int 子字符串, 指定索引
substring(int start) String 从指定位置开始截取字符串,默认到末尾。
substring(int start,int end) String 截取范围是[start,end)

String的常用转换方法:

方法名 返回值 说明
getBytes() byte[] 把字符串转换为字节数组。
toCharArray() char[] 把字符串转换为字符数组。
String valueOf() char[] 把传入的变量转成字符串。
toLowerCase() String 把字符串转成小写。
toUpperCase() String 把字符串转成大写。
concat(String str) String 把字符串拼接。

String类其他常用方法:

方法名 返回值 说明
replace(char old,char new) String 返回一个新的字符串,它是通过用 newChar 替换
此字符串中出现的所有 oldChar 得到的。
replace(String old,String new) String 使用指定的字面值替换序列替换此字符串
所有匹配字面值目标序列的子字符串。
trim() String 返回字符串的副本,忽略前导空白和尾部空白。
compareTo(String str) int 按字典顺序比较两个字符串。
compareToIgnoreCase(String str) int 按字典顺序比较两个字符串,不考虑大小写。
split(String regex) String[] 根据给定正则表达式的匹配拆分此字符串。
split(String regex,int limit) String[] 根据匹配给定的正则表达式来拆分此字符串。

String、StringBuffer和StringBuilder

  • String 类对象不可变,一旦修改 String的值就是隐形的重建了一个新的对象,释放了原 String对象
  • StringBuffer和StringBuilder类是可以通过append()、insert()、reverse()…等方法来修改值。创建的对象是可变
  • StringBuffer:线程安全的; StringBuilder:线程非安全的
  • 字符串连接 String 的 + 比 StringBuffer(StringBuilder) 的 Append() 性能差了很多
  • 三者在执行速度方面的比较:StringBuilder > StringBuffer > String

四、BigDecimal类

为了能精确表示、计算浮点数,Java提供了BigDecimal类,该类提供了大量的构造器用于创建BigDecimal对象,包括把所有的基本数值型变量转换成一个BigDecimal对象,也包括利用数字字符串、数字字符数组来创建BigDecimal对象。

常用构造器:

构造器 说明
BigDecimal(char[] in) 将 BigDecimal 的字符数组表示形式转换为 BigDecimal,
接受与BigDecimal(String) 构造方法相同的字符序列。
BigDecimal(double val) 将 double 转换为 BigDecimal(double 的二进制浮点值准确的十进制表示形式)。
BigDecimal(int val) 将 int 转换为 BigDecimal。
BigDecimal(long val) 将 long 转换为 BigDecimal。
BigDecimal(String val) 将 BigDecimal 的字符串表示形式转换为 BigDecimal。

常用方法

方法 返回值 说明
valueOf(double val) BigDecimal 将 double 转换为 BigDecimal。
valueOf(long val) BigDecimal 将 long 值转换为具有零标度的BigDecimal。
abs() BigDecimal 值为此 BigDecimal 的绝对值,标度为 this.scale()。
add(BigDecimal augend) BigDecimal
subtract(BigDecimal subtrahend) BigDecimal
multiply(BigDecimal multiplicand) BigDecimal
divide(BigDecimal divisor) BigDecimal
pow(int n) BigDecimal 乘方
compareTo(BigDecimal val) int 比较
byteValue() byte 将此 BigDecimal 转换为 byte
byteValueExact() byte 将此 BigDecimal 转换为 byte,以检查丢失的信息。
shortValue() short
shortValueExact() short
intValue() int
intValueExact() int
longValue() long
longValueExact() long
floatValue() float
doubleValue() double
toString() String 返回此 BigDecimal 的字符串表示形式,如果需要指数,则使用科学记数法。

注意:在把浮点型数据转为BigDecimal时不建议使用构造器的方式,推荐使用valueOf()方法或者使用形参为字符串的构造器。

五、Date和Calendar类

Java提供了Date类来处理日期、时间(此处的Date是指java.util包下的Date类,而不是java.sql包下的Date类),Date对象既包含日期,也包含时间。Date类从JDK1.0起就开始存在了,因为它历史悠久,所以它的大部分构造器、方法都已经过时,不再推荐使用了。

Data构造类

Java.util.Date的构造器还剩下两个构造器,其他都已经过时(@Deprecated注解,表示已经不再推荐使用,使用会有警告,并且可以会导致程序性能或者安全性方面的问题)

构造器 说明
Date() 分配 Date 对象并初始化此对象,以表示分配它的时间(精确到毫秒)。
Date(long date) 分配 Date 对象并初始化此对象,以表示自从标准基准时间以来的指定毫秒数。

Date类方法

Java.util.Date的方法也剩下几个,其他都过时了

方法 返回值 说明
after(Date when) boolean 测试此日期是否在指定日期之后。
before(Date when) boolean 测试此日期是否在指定日期之前。
clone() Object 返回此对象的副本。
compareTo(Date anotherDate) int 比较两个日期的顺序。
equals(Object obj) boolean 比较两个日期的相等性。
getTime() long 返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
setTime(long time) void 设置此 Date 对象,以表示 1970 年 1 月 1 日 00:00:00 GMT以后 time 毫秒的时间点。

由于Date类过于古老,许多的构造器和方法都已经过时。Java推荐使用Calendar来完成时间计算等操作。

Calendar类中关于时间的属性

常量 描述
Calendar.YEAR 年份
Calendar.MONTH 月份
Calendar.DATE 日期
Calendar.DAY_OF_MONTH 日期
Calendar.HOUR 12小时制的小时
Calendar.HOUR_OF_DAY 24小时制的小时
Calendar.MINUTE 分钟
Calendar.SECOND
Calendar.DAY_OF_WEEK 星期几

Calendar类中常用方法

方法 返回值 说明
getInstance() Calendar 使用默认时区和语言环境获得一个日历。
get(int field) int 返回给定日历字段的值。
set(int field, int value) void 将给定的日历字段设置为给定值。
add(int field, int amount) void 为给定的日历字段添加或减去指定的时间量。
roll(int field, int amount) void 向指定日历字段添加指定(有符号的)时间量
getTime() Date 返回一个表示此 Calendar 时间值的 Date 对象。
setTime(Date date) void 使用给定的 Date 设置此 Calendar 的时间。

六、Math类

Java提供了Math工具类来完成复杂的运算,Math类是一个工具类,构造器被private的,无法创建Math类的对象;Math类中的所有方法都是静态方法(类方法),可以直接通过类名来调用它们。Math类还提供了两个类变量:PI(圆周率)和E(自然对数的底数)

public class MathDemo {
public static void main(String[] args)
{
	/*‐‐‐‐‐‐‐‐‐两个类变量‐‐‐‐‐‐‐‐‐‐‐*/
	System.out.println("‐‐‐‐‐‐‐‐‐两个类变量‐‐‐‐‐‐‐‐‐‐‐");
	System.out.println("Math.PI = "+ Math.PI);
	System.out.println("Math.E = "+ Math.E);
	/*‐‐‐‐‐‐‐‐‐三角运算‐‐‐‐‐‐‐‐‐*/
	System.out.println("‐‐‐‐‐‐‐‐‐三角运算‐‐‐‐‐‐‐‐‐‐‐");
	// 将弧度转换角度
	System.out.println("Math.toDegrees(1.57) = " + Math.toDegrees(1.57));
	// 将角度转换为弧度
	System.out.println("Math.toRadians(90) = " + Math.toRadians(90));
	// 计算反余弦,返回的角度范围在 0.0 到 pi 之间。
	System.out.println("Math.acos(1.2) = " + Math.acos(1.2));
	// 计算反正弦;返回的角度范围在 ‐pi/2 到 pi/2 之间。
	System.out.println("Math.asin(0.8) = " + Math.asin(0.8));
	// 计算反正切;返回的角度范围在 ‐pi/2 到 pi/2 之间。
	System.out.println("Math.atan(2.3) = " + Math.atan(2.3));
	// 计算三角余弦。
	System.out.println("Math.cos(1.57) = " + Math.cos(1.57));
	// 计算值的双曲余弦。
	System.out.println("Math.cosh(1.2 ) = " + Math.cosh(1.2 ));
	// 计算正弦
	System.out.println("Math.sin(1.57 ) = " + Math.sin(1.57 ));
	// 计算双曲正弦
	System.out.println("Math.sinh(1.2 ) = " + Math.sinh(1.2 ));
	// 计算三角正切
	System.out.println("Math.tan(0.8 ) = " + Math.tan(0.8 ));
	// 计算双曲正切
	System.out.println("Math.tanh(2.1 ) = " + Math.tanh(2.1 ));
	// 将矩形坐标 (x, y) 转换成极坐标 (r, thet));
	System.out.println("Math.atan2(0.1, 0.2) = " + Math.atan2(0.1, 0.2));
	/*‐‐‐‐‐‐‐‐‐取整运算‐‐‐‐‐‐‐‐‐*/
	System.out.println("‐‐‐‐‐‐‐‐‐取整运算‐‐‐‐‐‐‐‐‐‐‐");
	// 取整,返回小于目标数的最大整数。
	System.out.println("Math.floor(‐1.2 ) = " + Math.floor(1.2 ));
	// 取整,返回大于目标数的最小整数。
	System.out.println("Math.ceil(1.2) = " + Math.ceil(1.2));
	// 四舍五入取整
	System.out.println("Math.round(2.3 ) = " + Math.round(2.3 ));
	/*‐‐‐‐‐‐‐‐‐乘方、开方、指数运算‐‐‐‐‐‐‐‐‐*/
	System.out.println("‐‐‐‐‐‐‐‐‐乘方、开方、指数运算‐‐‐‐‐‐‐‐‐‐‐");
	// 计算平方根。
	System.out.println("Math.sqrt(2.3 ) = " + Math.sqrt(2.3 ));
	// 计算立方根。
	System.out.println("Math.cbrt(9) = " + Math.cbrt(9));
	// 返回欧拉数 e 的n次幂。
	System.out.println("Math.exp(2) = " + Math.exp(2));
	// 返回 sqrt(x2 +y2)
	System.out.println("Math.hypot(4 , 4) = " + Math.hypot(4 , 4));
	// 按照 IEEE 754 标准的规定,对两个参数进行余数运算。
	System.out.println("Math.IEEEremainder(5 , 2) = " + Math.IEEEremainder(5 , 2));
	// 计算乘方
	System.out.println("Math.pow(3, 2) = " + Math.pow(3, 2));
	// 计算自然对数
	System.out.println("Math.log(12) = " + Math.log(12));
	// 计算底数为 10 的对数。
	System.out.println("Math.log10(9) = " + Math.log10(9));
	// 返回参数与 1 之和的自然对数。
	System.out.println("Math.log1p(9) = " + Math.log1p(9));
	/*‐‐‐‐‐‐‐‐‐符号相关的方法‐‐‐‐‐‐‐‐‐*/
	System.out.println("‐‐‐‐‐‐‐‐‐符号相关的方法‐‐‐‐‐‐‐‐‐‐‐");
	// 计算绝对值。
	System.out.println("Math.abs(‐4.5) = " + Math.abs(4.5));
	// 符号赋值,返回带有第二个浮点数符号的第一个浮点参数。
	System.out.println("Math.copySign(1.2, ‐1.0) = " + Math.copySign(1.2,1.0));
	// 符号函数;如果参数为 0,则返回 0;如果参数大于 0,
	// 则返回 1.0;如果参数小于 0,则返回 ‐1.0。
	System.out.println("Math.signum(2.3) = " + Math.signum(2.3));
	/*‐‐‐‐‐‐‐‐‐大小比较相关的方法‐‐‐‐‐‐‐‐‐*/
	System.out.println("‐‐‐‐‐‐‐‐‐大小比较相关的方法‐‐‐‐‐‐‐‐‐‐‐");
	// 找出最大值
	System.out.println("Math.max(2.3 , 4.5) = " + Math.max(2.3 , 4.5));
	// 计算最小值
	System.out.println("Math.min(1.2 , 3.4) = " + Math.min(1.2 , 3.4));
	// 返回第一个参数和第二个参数之间与第一个参数相邻的浮点数。
	System.out.println("Math.nextAfter(1.2, 1.0) = " + Math.nextAfter(1.2, 1.0));
	// 返回比目标数略大的浮点数
	System.out.println("Math.nextUp(1.2 ) = " + Math.nextUp(1.2 ));
	// 返回一个伪随机数,该值大于等于 0.0 且小于 1.0。
	System.out.println("Math.random() = " + Math.random());
	}
}

七、Random类

Random类专门用于生成一个伪随机数的类,其产生的随机数是根据种子和顺序决定的;ThreadLocalRandom类是Java 7新增的一个类,它是Random的增强版。在并发访问的环境下,呆证系统具有更好的线程安全性。

构造器

构造器 说明
Random() 创建一个新的随机数生成器。
Random(long seed) 使用单个 long 种子创建一个新的随机数生成器。

常用方法

方法 返回值 说明
nextBoolean() boolean 返回下一个伪随机数
nextBytes(byte[] bytes) void 生成随机字节并将其置于用户提供的 byte 数组中。
nextDouble() double
nextFloat() float
nextGaussian() double
nextInt() int
nextInt(int n) int 返回[o,n)
nextLong() long
setSeed(long seed) void 设置此随机数生成器的种子。

注意:Random生成的随机数是伪随机数

只要两个Random对象的种子相同,而且方法的调用顺序也相同,产生的随机数相同。

import java.util.Random;

public class RandomDemo2 {
	public static void main(String[] args)
	{
		//只要两个Random对象的种子相同,而且方法的调用顺序也相同,产生的随机数相同
		//Random产生的数字并不是真正随机的,而是一种伪随机
		Random r1 = new Random(16);
		System.out.println("第一个种子为16的Random对象");
		System.out.println("r1.nextBoolean() = " + r1.nextBoolean());
		System.out.println("r1.nextInt() = " + r1.nextInt());
		System.out.println("r1.nextDouble() = " + r1.nextDouble());
		System.out.println("r1.nextGaussian() = " + r1.nextGaussian());
		System.out.println("‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐");
		Random r2 = new Random(16);
		System.out.println("第二个种子为16的Random对象");
		System.out.println("r2.nextBoolean() = " + r2.nextBoolean());
		System.out.println("r2.nextInt() = " + r2.nextInt());
		System.out.println("r2.nextDouble() = " + r2.nextDouble());
		System.out.println("r2.nextGaussian() = " + r2.nextGaussian());
		System.out.println("‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐");
		Random r3 = new Random(16);
		System.out.println("第三个种子为16的Random对象");
		System.out.println("r3.nextBoolean() = " + r3.nextBoolean());
		System.out.println("r3.nextInt() = " + r3.nextInt());
		System.out.println("r3.nextDouble() = " + r3.nextDouble());
		System.out.println("r3.nextGaussian() = " + r3.nextGaussian());
	}
}

重写object.tostring方法

object类里的toString只是把字符串的直接打印,数字的要转化成字符再打印,而对象,则直接打印该对象的hash码(它的值大概就是等于getClass().getName()+’@’+Integer.toHexString(hashCode()))。
重写tostring,每执行System.out.println() 会调用重写的toString 方法,情况则会根据重写的方法打印输出成自己想得到的格式。

发布了54 篇原创文章 · 获赞 3 · 访问量 3648

猜你喜欢

转载自blog.csdn.net/magic_jiayu/article/details/104130255