Java基础教程——System类

System类

java.lang.System类代表当前Java程序的运行平台。

|-可以做输入输出,垃圾回收;(此处不讲)
|-可以获取时间;
|-可以获取环境变量;
|-可以获取系统信息;
|-可以获取对象的原始HashCode。(比如String类就改写了hashCode方法,不能唯一地标识一个对象)

获取时间

public class System1时间 {
	public static void main(String[] args) {
		System.out.println("--currentTimeMillis():UTC(世界标准时间) 1970.1.1开始到现在的时间差");
		System.out.println("毫秒:" + System.currentTimeMillis());
		System.out.println("nanoTime()只能用于测量已过的时间");
		System.out.println("纳秒:" + System.nanoTime());
	}
}

System.currentTimeMillis()可以用户计算一段代码运行所消耗的时间。

System.nanoTime()精确度太高,硬件环境不一定能精确到纳秒,因此这个方法并不常用。


获取环境变量

import java.util.Map;
public class System2环境变量 {
	public static void main(String[] args) {
		String _环境变量名 = "JAVA_HOME";
		System.out.println(_环境变量名 + " = " + System.getenv(_环境变量名));
		System.out.println("-----环境变量(全部)-----");
		Map<String, String> env = System.getenv();
		for (String name : env.keySet()) {
			System.out.println(name + " = " + env.get(name));
		}
	}
}

获取系统信息

import java.util.Properties;
public class System3getProperty {
	public static void main(String[] args) {
		System.out.println(System.getProperty("os.name"));
		System.out.println(System.getProperty("user.dir"));// 用户工作路径
		System.out.println("-----System Property(ALL)-----");
		Properties props = System.getProperties();
		for (Object k : props.keySet()) {
			String v = props.getProperty(k.toString());
			System.out.println(k);
			System.out.println(k + " = " + v);
		}
	}
}

获取对象的原始HashCode

(比如String类就改写了hashCode方法,不能唯一地标识一个对象)

public class System4IdentityHashCode {
	public static void main(String[] args) {
		System.out.println("---identityHashCode():不同对象,此结果必不同---");
		System.out.println("---因为hashCode()可能被重写(比如String类),无法准确确定对象---");
		// s1和s2是两个不同对象
		String s1 = new String("Hello");
		String s2 = new String("Hello");
		// String重写了hashCode()方法——改为“根据字符序列计算hashCode值”,
		// 因为s1和s2的字符序列相同,所以它们的hashCode()相同
		// (和equals无关,equals不是根据hashCode判断,但是也是根据字符序列比较,殊途同归)
		System.out.println("new String 1.hashCode() = " + s1.hashCode());
		System.out.println("new String 2.hashCode() = " + s2.hashCode());
		// s1和s2是不同的字符串对象,所以它们的identityHashCode值不同
		System.out.println("new String 1.identityHashCode() = " + System.identityHashCode(s1));
		System.out.println("new String 2.identityHashCode() = " + System.identityHashCode(s2));
		String s3 = "Java";
		String s4 = "Java";
		// s3和s4是相同的字符串对象,所以它们的identityHashCode值相同
		System.out.println("String 3.identityHashCode() = " + System.identityHashCode(s3));
		System.out.println("String 4.identityHashCode() = " + System.identityHashCode(s4));
	}
}

运行结果(每次运行的结果可能不同)

---identityHashCode():不同对象,此结果必不同---
---因为hashCode()可能被重写(比如String类),无法准确确定对象---
new String 1.hashCode() = 69609650
new String 2.hashCode() = 69609650
new String 1.identityHashCode() = 366712642
new String 2.identityHashCode() = 1829164700
String 3.identityHashCode() = 2018699554
String 4.identityHashCode() = 2018699554
原文地址:https://www.cnblogs.com/tigerlion/p/11179180.html