引言:
Math类
Object类
Objects类
Math
Math 类包含用于执行基本数学运算的方法,如初等指数、对数、平方根和三角函数。
包路径
构造方法
直接通过Math调用,没有构造函数
常用方法
1 2 3 4 5
| public static double abs(double num) public static double ceil(double num) public static double floor(double num) public static long round(double num) Math.PI
|
示例代码
1 2 3 4 5 6 7
| int x = -8; double y = 2.6; System.out.println(Math.abs(x)); System.out.println(Math.ceil(y)); System.out.println(Math.floor(y)); System.out.println(Math.round(y)); System.out.println(Math.PI);
|
Object
类 Object 是类层次结构的根类。
每个类都使用 Object 作为超类。所有对象(包括数组)都实现这个类的方法。
包路径
构造方法
常用方法
1 2 3 4 5 6
| public String toString()
public boolean equals(Object obj)
|
示例代码
toString
1 2 3 4 5
| father f = new father(); String str = f.toString(); System.out.println(str); System.out.println(f);
|
但是直接打印一个对象的地址没有什么意义,我们重写它的String方法
1 2 3 4 5 6 7 8 9
| public class father { public String name; @Override public String toString(){ return "Person:"+name; } }
|
equals
1 2 3 4 5 6 7 8 9 10
| public boolean equals(Object obj){ return(this == obj); }
father f1 = new father("A"); father f2 = new father("A"); System.out.println(f1.equals(f2)); f1 = f2; System.out.println(f1.equals(f2));
|
但是我们比较他们的地址没有意义,所以我们重写一下equals方法
1 2 3 4 5 6
| @Override public boolean equals(Object obj){ father f = (father)obj; return this.name.equals(f.name); }
|
又考虑到传入空或者传入其他类型的对象,可能会报错,我们完善一下重写的方法
使用ALT+insert即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; father father = (father) o; return Objects.equals(name, father.name); }
@Override public int hashCode() { return Objects.hash(name); }
|
Objects
JDK7添加,提供了一些静态方法来操作对象,这些方法是空指针安全的
包路径
构造函数
无构造方法,直接调用Objects来使用
常用方法
1 2 3 4 5 6 7 8
| public static boolean equals(Object a,Object b) { return (a==b) || ( a!=null && a.equals(b) );
}
requireNonNull()
|
示例代码
直接使用Obejct的equals会报空指针异常
1 2 3
| String s1 = null; s1.equals('a');
|
而Obejcts不会报错
1 2
| String s1 = null; Objects.equals(s1, "a");
|
查看是否为空对象
1 2
| String s1 = null; Objects.equals(s1, "a");
|