java提供了一系列的工具类,我们应用的时候可以访问它们的属性和方法,但是工具类很多,记住常用的即可!使用的时候就去API帮助文档手册查找,有离线的和在线版本的,离线的百度搜索一下都能找到
Object
之前我们说过Object是所有类的根类,那么说具体的工具类之前,我们先说一下Object
说白了Object也是一个类,那么肯定也有对应的方法
Object所有方法的作用在API帮助文档手册都能找到,这里就介绍几个方法,测试之前先写一段代码
public class MobilePhone {
private String brand;
private int price;
public MobilePhone() {
}
public MobilePhone(String brand, int price) {
this.brand = brand;
this.price = price;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
public class TestMobilePhone {
public static void main(String[] args) {
MobilePhone phone=new MobilePhone();
//子类没对Object重写,都调用的是Object类的方法
//getClass():获取类的全限定名(包名+类名),执行结果:class com.ty.Packaging.MobilePhone
System.out.println(phone.getClass());
//hashCode():获取哈希码,执行结果:703360008,注意:每次执行hashCode都可能不同
//哈希码:将对象在堆中的地址,进行哈希算法,会返回一个码称为哈希码
System.out.println(phone.hashCode());
//获取该对象字符串的表示信息:执行结果:com.ty.Packaging.MobilePhone@519dcf69
//默认此字符串的含义:getClass().getName() + "@" + Integer.toHexString(hashCode());
// Integer.toHexString()的意思是将一个数用十六进制展示
System.out.println(phone.toString());
MobilePhone phone1=new MobilePhone("P40",4488);
MobilePhone phone2=new MobilePhone("P40",4488);
//比较phone1对象和phone2对象内容是否相等,此处现在执行结果是false,因为默认调用的Object里的equals方法还是用==判断,比较的是两个对象的地址是否相等,return (this == obj);
System.out.println(phone1.equals(phone2));
}
}
//要想显示对象信息的时候好看一些,判断2个对象内容是否相等而不是比较地址的话,MobilePhone就可以重写toString和equals方法
//自己进行重写equals
@Override
public boolean equals(Object obj) {
MobilePhone phone = (MobilePhone) obj;
if (this.getBrand() == phone.getBrand() && this.getPrice() == phone.getPrice()) {
return true;
}
return false;
}
//IDE帮助我们重写equals
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MobilePhone phone = (MobilePhone) o;
return price == phone.price &&
Objects.equals(brand, phone.brand);
}
//自己进行重写toString
@Override
public String toString() {
return "手机品牌是:"+this.getBrand()+"手机价格是:"+this.getPrice();
}
//IDE帮助我们重写toString
@Override
public String toString() {
return "MobilePhone{" +
"brand='" + brand + '\'' +
", price=" + price +
'}';
}
//这样 System.out.println(phone1.equals(phone2));输出的就是:true
//System.out.println(phone1.toString());输出的就是:MobilePhone{brand='P40', price=4488}
包装类
之前我们都是用基本都是基本类型存储数据的,基本类型的好处就是不需要new创建,也就不会在堆中开辟空间,直接在栈中存储会更加高效。但是我们了解java最主要的就是面向对象的特性,即能操作对象的属性和方法,基本类型就不能满足要求了,然后java就引进了包装类
基本数据类型 | 包装类 | 父类 |
---|---|---|
byte | Byte | Number------->Object |
boolean | Boolean | Object |
short | Short | Number------->Object |
char | Character | Object |
int | Integer | Number------->Object |
long | Long | Number------->Object |
float | Float | Number------->Object |
double | Double | Number------->Object |
Integer
拿Integer做案例来进行讲解,此类掌握了之后其它的包装类大同小异
从上面API帮助文档手册可以看出几个信息,所有的类都可以从 API帮助文档手册上查看!
-
所属包:Integer类所属java.lang下,使用的时候无需导包
-
继承信息:Integer类继承自Number类,再往上继承自Object类
-
实现信息:Integer类实现Serializable和Comparable<Integer>接口
-
类的附加信息:Integer类被final关键字修饰,不能有子类继承
-
类的描述信息:是对基本数据类型的封装,Integer是对int的封装。而且此类提供了处理int的时候的属性和方法
-
类的开始生效版本:JDK1.0
-
再接着往下看API你能看到具体的操作方法,也能看到具体操作的描述信息,这里就不截出来了
演示一下操作方法,详细的还是看API比较好
//操作属性
System.out.println(Integer.MAX_VALUE); //返回最大值
System.out.println(Integer.MIN_VALUE); //返回最小值
//构造方法
Integer integer1 = new Integer(10);
Integer integer2 = new Integer("123");
System.out.printf("integer1:%d , integer2:%d", integer1, integer2);
简单看一下源码的处理流程:
//传进的int数据传进底层要封装进的value里
private final int value;
public Integer(int value) {
this.value = value;
}
//传进的String数据调用parseInt,将String转换成int类型数据,然后传进底层要封装进的value里,如果转换不成功就报NumberFormatException异常
public Integer(String s) throws NumberFormatException {
this.value = parseInt(s, 10);
}
另外包装类型和基本数据类型是互相能进行转换的,基本数据类型转换为包装类型称为装箱,反之成为拆箱
在jdk5之后增加了一种机制,提供了自动装箱和自动拆箱这种特性,能很好更好的完成转换功能
Integer integer = 18; //自动装箱,基本类型-》包装类型
System.out.println(integer);
int num = integer1;
System.out.println(num); //自动拆箱,包装类型-》基本类型
看一下反编译之后的代码
可见底层实现自动装箱就是调用了valueOf()方法,自动拆箱就是调用了intValue()方法
看一下ValueOf()方法的实现
private static class IntegerCache {
static final int low = -128;
static final int high;
static final Integer cache[];
static {
int h = 127;
high = h; //high = 127
cache = new Integer[(high - low) + 1]; //cache = new Integer[(127 - (-128)) + 1]
// 也就是cache[] = new Integer[256]
int j = low; // int j = -128
for(int k = 0; k < cache.length; k++)
cache[k] = new Integer(j++); //cache[256]={-128,-127,-126,......,126,127}
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high) //if(i >= -128 && i <= 127)
return IntegerCache.cache[i + (-IntegerCache.low)]; //return IntegerCache.cache[i + (-128)]
return new Integer(i); //不符合范围就new一个
}
//总结:如果值是-128到127之间就从IntegerCache.cache数组中获取,如果不在这个范围,就new
//这段代码就是调用了上面那段valueOf的代码,判断实现
Integer integer3 = 12;
Integer integer4 = 12;
Integer integer5 = 128;
Integer integer6 = 128;
System.out.println(integer3 == integer4); // true,比较的是数值
System.out.println(integer5 == integer6); // false,比较的是地址
再演示一个方法:
Integer integer7=10;
Integer integer8=12;
System.out.println(integer.compareTo(integer8));// 执行结果:-1
/*
源码:
public int compareTo(Integer anotherInteger) {
return compare(this.value, anotherInteger.value);
}
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
*/
Character
可以从API帮助文档手册查看具体信息,查看方法参考上面的Integer,这里演示几个常用的方法!
public class TestCharacter {
public static void main(String[] args) {
Character ch=new Character('a');
System.out.println(Character.isDigit(ch)); //判断是否为数字
System.out.println(Character.isLetter(ch)); //判断是否为字母
System.out.println(Character.isUpperCase(ch)); //判断是否为大写
System.out.println(Character.isLetter(ch)); //判断是否为小写
System.out.println(Character.isWhitespace(ch)); //判断是否为空格
System.out.println(Character.toUpperCase(ch)); //转换为大写
System.out.println(Character.toLowerCase('A')); //转换为小写
}
}
字符串类
String
除了从API手册上查看此类的信息,还可以从源码上查看
package java.lang;
/**
* The <code>String</code> class represents character strings. All
* string literals in Java programs, such as <code>"abc"</code>, are
* implemented as instances of this class.
* 类的上面有许多注释,这些注释都不是白来的,API的描述信息也是从这些注释得来的
* @since JDK1.0
*/
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
通过看源码,可得以下基本信息:
-
所属包:String类所属java.lang下,使用的时候无需导包
-
继承信息:String类继承自Object类
-
实现信息:String类实现Serializable,Comparable<Integer>和CharSequence接口
-
类的附加信息:String类被final关键字修饰,不能有子类继承;"abc"是String类下的一个具体的对象
-
类的描述信息:String是对字符数组封装,String的内容存放在char value[]中,而且此数组被final修饰,即字符串不可被修改
-
类的开始生效版本:JDK1.0
-
再接着往下看源码你能看到具体的操作方法,而且也能看见对应操作的描述信息
下面演示一下具体操作,详细的你最好还是看API或者源码
//创建字符串
public class TestString {
public static void main(String[] args) {
/**这种方式先在常量池中查看是否具有"abc"的存储空间
* 如果有的话直接指向,如果没有就先创建再指向
* str1指向的是常量池的空间地址
*/
String str1 = "abc";
/**new这种方式,会先在堆中开辟一个空间,里面有个value属性,指向常量池的空间
* 如果常量池中有"abc"的话 value直接指向,如果没有就先创建然后 value再指向
* new指向的是堆中的空间地址
*/
String str2 = new String("abc");
String str3 = new String(new char[]{'a', 'b', 'c'});
String str4 = "hello";
String str5 = str4 + "java";
}
}
此外还有一种方式
String str4 = "hello";
String str5 = str4 + "java";
/*这种方式其实是创建了StringBuilder字符串类,通过反汇编的方式,可能有利于理解,反汇编的命令:javap -c class文件
39: ldc #6 // String hello
String str4 = "hello";
41: astore 4
43: new #7 // class java/lang/StringBuilder
new StringBuilder
46: dup
47: invokespecial #8 // Method java/lang/StringBuilder."<init>":()V
StringBuilder sb=new StringBuilder();
50: aload 4
52: invokevirtual #9 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
sb.append(str4);
55: ldc #10 // String java
String str = "java";
57: invokevirtual #9 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
sb.append(str);
60: invokevirtual #11 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
将StringBuilder类型转换成String类型
//常用方法
System.out.println(str1.length()); //获取字符串的长度
System.out.println(str1.isEmpty()); //判断字符串是否为空
System.out.println(str1.charAt(1)); //获取字符串指定索引的单个字符,索引从0开始
System.out.println(str1.indexOf("b")); //获取字符在字符串中第一次出现的索引,如果找不到,返回-1
System.out.println(str1.lastIndexOf("b")); //获取字符在字符串中最后一次出现的索引,如果找不到,返回-1
System.out.println(str1.substring(1)); //截取指定范围的子串
System.out.println(str1.equals("abcd")); //判断两个字符串内容是否相等,Object类之下的系统子类基本都重写了equals方法
System.out.println(str1.equalsIgnoreCase("ABCD")); //忽略大小写,判断内容是否相等
System.out.println(str1.compareTo("abcd")); //按照Unicode的顺序比较两个字符串,如果前者大,则返回正数,后者大,则返回负数,如果相等,返回0
System.out.println(str1.toUpperCase()); //转换成大写
System.out.println("ABCD".toLowerCase()); //转换成小写
System.out.println(str1.concat("def")); //拼接字符串
System.out.println("智障,CNM".replace("CNM", "xxx")); //替换字符串中的字符
String poem = "E:\\附加项目\\附加-project";
String[] split = poem.split("\\\\"); //以指定字符分割字符串
for (int i = 0; i < split.length; i++) {
System.out.println(split[i]);
}
str=" abc ";
System.out.println(str);
System.out.println(str.trim()); //去除前后空格
String str = "hello";
char[] array = str.toCharArray(); //转换成字符数组
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
String name = "john";
int age = 10;
double score = 98.3 / 3;
char gender = '男';
//format():格式字符串,占位符:%s 字符串 %c 字符 %d 整型 %.f 浮点型,.f之前可以加数字表示保留几位小数
String info = String.format("我的名字%s,年龄:%d,考试成绩:%f,性别:%c", name, age, score, gender);
System.out.println(info);
了解一下equals和compareTo的源码
/* String str1 = "abcd";
String str2 = "abcd"
System.out.println(str1.equals(str2));
*/
private final char value[];
public boolean equals(Object anObject) {
if (this == anObject) { //if (str1 == str2),比较两个对象的地址,相同就直接返回true
return true;
}
if (anObject instanceof String) { //判断传入的str2是不是String的实例,不是的话直接返回false
String anotherString = (String)anObject; // Object类型的str2向下转型为String类型
int n = value.length; // n = str1.length
if (n == anotherString.value.length) { // if (n == str.length),判断长度不等的话就返回false
char v1[] = value; // v1[] = str1{'a','b','c','d'}
char v2[] = anotherString.value; // v2[] = str2{'a','b','c','d'}
int i = 0;
while (n-- != 0) { //对数组进行遍历
if (v1[i] != v2[i]) //一位一位取出来进行遍历,对应位不等的话的话就返回false
return false;
i++;
}
return true;
}
}
return false;
}
/* String str1 = "abcd";
String str2 = "abcd"
System.out.println(str1.equals(str2));
*/
private final char value[];
public int compareTo(String anotherString) {
int len1 = value.length; // len1 = str1的长度:4
int len2 = anotherString.value.length; // len2 = str2的长度:4
int lim = Math.min(len1, len2); // 取小的那个值,即:lim = 4
char v1[] = value; // v1[] = str1{'a','b','c','d'}
char v2[] = anotherString.value; // v2[] = str2{'a','b','c','d'}
int k = 0;
while (k < lim) {
char c1 = v1[k]; //c1 = v1[0],c1 = v1[1],c1 = v1[2],c1 = v1[3]
char c2 = v2[k];// c2 = v2[0],c2 = v2[1],c2 = v2[2],c2 = v2[3]
if (c1 != c2) { // 分别对应判断是否相等,如果相等直接k++,如果不等先返回两个数的差值,然后进行k++
return c1 - c2;
}
k++;
}
return len1 - len2; //如果经过上面那个步骤判断每位数都相同,两个数长度不同的话就返回它俩的长度差
}
String这种方式创建字符串,因为它是不可变的每次增加的时候实际上是重新开辟空间存储
//衡量一些代码走完所需的时间
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
str += "hello";
}
long end = System.currentTimeMillis();
System.out.println("耗时:" + (end - start));
针对这种效率问题,java提供了另外一种表示字符串的类StringBuilder 和 StringBuffer
StringBuffer
还是简单看一下源码
/**
* A thread-safe, mutable sequence of characters.
* A string buffer is like a {@link String}, but can be modified. At any
* point in time it contains some particular sequence of characters, but
* the length and content of the sequence can be changed through certain
* method calls.
* @since JDK1.0
*
* 线程安全[多线程]的可变字符序列,字符串缓冲区类似于String,可以被修改,可以通过某些方法调用来更改序列的长度和内容。JDK1.0就有
*/
public final class StringBuffer
extends AbstractStringBuilder
implements java.io.Serializable, CharSequence
{
//继承自AbstractStringBuilder类
/**
* A mutable sequence of characters.
* <p>
* Implements a modifiable string. At any point in time it contains some
* particular sequence of characters, but the length and content of the
* sequence can be changed through certain method calls.
*
* 可变的字符序列,实现可修改的字符串。它在任何时间点都包含某些特殊的字符序列,但是可以通过某些方法调用来更改序列的长度和内容。
* @author Michael McCloskey
* @author Martin Buchholz
* @author Ulf Zibis
* @since 1.5
*/
abstract class AbstractStringBuilder implements Appendable, CharSequence {
/**
* The value is used for character storage.
*/
char[] value; //存放的是可变的字符数组
/**
* The count is the number of characters used.
*/
int count; //value数组中被使用的长度
//测试效率
public class TestStringBuffer {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
sb.append("hello"); //表示追加内容
}
long end = System.currentTimeMillis();
System.out.println("耗时:" + (end - start));
}
}
//同样一段代码StringBuffer比String的效率高
//常用方法
StringBuffer sb = new StringBuffer("好好学习");
System.out.println(sb); //执行结果:好好学习;调用的是toString()方法,return new String(value, 0, count)
//增加
sb.append(",");
sb.append("天天向上");
System.out.println(sb); //执行结果:好好学习,天天向上
//删除
sb.delete(4,sb.length());
System.out.println(sb); //执行结果:好好学习
//修改
sb.replace(2,sb.length(),"工作"); //替换
System.out.println(sb); //执行结果:好好工作
sb.insert(0,"dream!"); //插入
System.out.println(sb); //执行结果:dream!好好工作
//查找
sb=new StringBuffer("abcdef");
System.out.println(sb.charAt(3));
StringBuilder
/**
* A mutable sequence of characters. This class provides an API compatible
* with <code>StringBuffer</code>, but with no guarantee of synchronization.
* This class is designed for use as a drop-in replacement for
* <code>StringBuffer</code> in places where the string buffer was being
* used by a single thread (as is generally the case). Where possible,
* it is recommended that this class be used in preference to
* <code>StringBuffer</code> as it will be faster under most implementations.
* @since 1.5
*
* 可变的字符序列,此类提供一个与 StringBuffer 兼容的 API,但不保证同步(多线程问题)。该类被设计用作 StringBuffer 的一个简易
* 替换,用在字符串缓冲区被单个线程使用的时候。如果可能,建议优先采用该类,因为在大多数实现中,它比StringBuffer要快,JDK1.5有
*/
public final class StringBuilder
extends AbstractStringBuilder
implements java.io.Serializable, CharSequence
{
StringBuilder 和 StringBuffer方法是一样的,所以使用和StringBuffer一样,这里就不演示了
总结:String、StringBuffer 和StringBuilder的比较
-
String:不可变字符序列
-
StringBuilder 和 StringBuffer 非常类似,均代表可变的字符序列,而且方法也一样
-
StringBuffer:可变字符序列、效率较高(增删)、线程安全
-
StringBuilder(JDK1.5):可变字符序列、效率最高、线程不安全
-
应用场景:
-
字符串很少修改,被多个对象引用,使用String, 比如配置信息等
-
字符串存在大量的修改操作,一般使用 StringBuffer 或 StringBuilder
-
单线程:使用 StringBuilder
-
多线程:使用StringBuffer
-
数学类
Math
/**
* The class {@code Math} contains methods for performing basic
* numeric operations such as the elementary exponential, logarithm,
* square root, and trigonometric functions.
*
* Math类包含用于执行基本数值运算的方法,例如基本指数,对数,*平方根和三角函数。
*/
public final class Math {
/**
* Don't let anyone instantiate this class.
*/
private Math() {} //构造器私有化代表不能创建Math对象
//往下看属性和方法能看出来都是被static关键字修饰,所以使用Math.来调用
//静态导包
import static java.lang.Math.*;
public class TestMath {
public static void main(String[] args) { //常用属性:
System.out.println(PI);
//常用方法:
System.out.println("随机数:" + random());//[0.0 ~ 1.0)
System.out.println("绝对值:" + abs(-80));
System.out.println("向上取值:" + ceil(9.1));
System.out.println("向下取值:" + floor(9.9));
System.out.println("四舍五入:" + round(3.5));
System.out.println("取大的那个值:" + max(3, 6));
System.out.println("取小的那个值:" + min(3, 6));
System.out.println("求幂:" + pow(2, 3));
System.out.println("求开方:" + sqrt(9));
}
}
Arrays类
/**
* This class contains various methods for manipulating arrays (such as
* sorting and searching). This class also contains a static factory
* that allows arrays to be viewed as lists.
*
*此类包含各种用于处理数组的方法(例如排序和搜索)。此类还包含一个静态工厂,该工厂可以将数组视为列表。
*/
public class Arrays {
// Suppresses default constructor, ensuring non-instantiability.
private Arrays() {}
//常用方法
Integer[] arr = {10, 25, 32, 65, 47, 125, 845, 52};
System.out.println(Arrays.toString(arr)); //对数组进行遍历
Arrays.sort(arr);//排序,默认升序
System.out.println(Arrays.toString(arr));
Arrays.sort(arr, new Comparator() { //自定义排序
@Override
public int compare(Object o1, Object o2) {
Integer n1 = (Integer) o1;
Integer n2 = (Integer) o2;
if (n1 > n2) {
return -1;
} else if (n1 < n2) {
return 1;
}
return 0;
}
});
System.out.println(Arrays.toString(arr));
Integer[] array = {85, 45, 25, 36, 521, 100};
Arrays.sort(array);
System.out.println(Arrays.toString(array));
// 二分法查找:找出指定数组中的指定元素对应的索引,必须是一个有序数组
// 如果找到,就是对应的下标
// 如果没有,就返回 -(low+1) low:应该存在的下标
System.out.println(Arrays.binarySearch(array, 455));
String[] strArr = new String[]{"a", "bc", "de", "fgh", "h", "e", "llo"};
//如果拷贝的长度在有效范围1 ~ arr.length , 就拷贝指定的个数
//拷贝的长度 > arr.length , 多余用null占位, 小于0就会报错
String[] newArr = Arrays.copyOf(strArr, 2); //复制数组
System.out.println(Arrays.toString(newArr));
String[] newArr2 = Arrays.copyOfRange(strArr, 2, 4); //区间复制,左开右闭
System.out.println(Arrays.toString(newArr2));
System.out.println(strArr.equals(newArr)); //判断数组的值是否相等
int[] arr2 = {10, 20, 30};
Arrays.fill(arr2, 40); // 数组的填充
System.out.println(Arrays.toString(arr2));
List<int[]> list = Arrays.asList(arr2); //将数组转换成list
System.out.println(list.size());
System类
/**
* The <code>System</code> class contains several useful class fields
* and methods. It cannot be instantiated.
*
* <p>Among the facilities provided by the <code>System</code> class
* are standard input, standard output, and error output streams;
* access to externally defined properties and environment
* variables; a means of loading files and libraries; and a utility
* method for quickly copying a portion of an array.
*
* System类包含几个有用的类字段和方法。无法实例化。
* System类提供的功能包括标准输入,标准输出和错误输出流。 访问外部定义的属性和环境变量;一种加载文件和库的方法; 以及用于快速
* 制阵列的一部分的实用方法。
* @author unascribed
* @since JDK1.0
*/
public final class System {
public static void main(String[] args) {
// arraycopy :复制数组元素,比较适合底层调用,一般使用Arrays.copyOf完成复制数组.
int[] src = {1, 2, 3}; //源数组
int[] dest = new int[3];//目标数组
/**解读
* @param src 源数组
* @param srcPos 源数组中的起始位置
* @param dest 目标数组
* @param destPos 目标数据中的起始位置
* @param length 要复制的数组元素的数量
*/
System.arraycopy(src, 1, dest, 1, 2);
System.out.print(Arrays.toString(dest));
System.out.println();
for (int i = 0; i < 10; i++) {
if (i == 6) {
System.exit(0); //退出程序
}
System.out.println(i);
}
BigInteger/BigDecimal类
/**
* Immutable arbitrary-precision integers. All operations behave as if
* BigIntegers were represented in two's-complement notation (like Java's
* primitive integer types). BigInteger provides analogues to all of Java's
* primitive integer operators, and all relevant methods from java.lang.Math.
* Additionally, BigInteger provides operations for modular arithmetic, GCD
* calculation, primality testing, prime generation, bit manipulation,
* and a few other miscellaneous operations.
*
* 不可变的任意精度整数,适合保存比较大的整型
*/
public class BigInteger extends Number implements Comparable<BigInteger> {}
/**
* Immutable, arbitrary-precision signed decimal numbers. A
* {@code BigDecimal} consists of an arbitrary precision integer
* <i>unscaled value</i> and a 32-bit integer <i>scale</i>. If zero
* or positive, the scale is the number of digits to the right of the
* decimal point. If negative, the unscaled value of the number is
* multiplied by ten to the power of the negation of the scale. The
* value of the number represented by the {@code BigDecimal} is
* therefore <tt>(unscaledValue × 10<sup>-scale</sup>)</tt>.
*
* 不可变,任意精度的带符号十进制数字,适合保存精度更高的浮点型(小数)
*/
public class BigDecimal extends Number implements Comparable<BigDecimal> {}
public class TestBig {
public static void main(String[] args) {
System.out.println("整数-------------------------------------------------------------------");
//long num=855451236958545452125L;存储不了
BigInteger num1 = new BigInteger("855451236958545452125");
System.out.println(num1);
//运算方法
BigInteger num2 = new BigInteger("41455288452565565656336655454588545");
System.out.println(num1.add(num2)); //加
System.out.println(num2.subtract(num1)); //减
System.out.println(num1.multiply(num2)); //乘
System.out.println(num2.divide(num1)); //除
System.out.println("浮点数-------------------------------------------------------------------");
//精度损失了
double d1 = 4567888888888888888888888888888888888888222222222222222222222222222222222222228888888.23;
System.out.println(d1);
BigDecimal d = new BigDecimal("45678888888888888888888888888888888888882222222222222222222222222222222222222222222222222222222222222222222222222222288888888888888888888888888.23");
BigDecimal d2 = new BigDecimal(33);
System.out.println(d);
System.out.println(d.add(d2)); //加
System.out.println(d.subtract(d2)); //减
System.out.println(d.multiply(d2)); //乘
//没有后面没有参数,则会提示:ArithmeticException:Non-terminating decimal expansion; no exact representable decimal result.
System.out.println(d.divide(d2, BigDecimal.ROUND_CEILING)); //除
}
}
日期类
使用的时候去查API手册即可!
第一代日期类
public class TestDate {
public static void main(String[] args) throws ParseException {
Date date= new Date();
System.out.println(date);
System.out.println(date.getTime()); //获取某个时间对应的毫秒数
//使用SimpleDateFormat进行格式化输出, "yyyy-MM-dd HH:mm:ss E" 各个字母是格式化符合,是规定好的
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
System.out.println(dateFormat.format(date));
//通过一个毫秒,得到对应的日期
Date d2 = new Date(1606924829078L);
System.out.println(dateFormat.format(d2));
//将一个String 格式化转成Date对象,s格式需要和dateFormat格式匹配,否则ParseException
String s="2020-02-03 00:01:40 星期四";
Date format = dateFormat.parse(s);
System.out.println(format.getTime());
}
}
格式化日期要求的字母格式
第二代日期类
第二代日期类,主要就是 Calendar类(日历)
/**
* The <code>Calendar</code> class is an abstract class that provides methods
* for converting between a specific instant in time and a set of {@link
* #fields calendar fields} such as <code>YEAR</code>, <code>MONTH</code>,
* <code>DAY_OF_MONTH</code>, <code>HOUR</code>, and so on, and for
* manipulating the calendar fields, such as getting the date of the next
* week. An instant in time can be represented by a millisecond value that is
* an offset from the <a name="Epoch"><em>Epoch</em></a>, January 1, 1970
* 00:00:00.000 GMT (Gregorian).
*
* Calendar类是一个抽象类,提供用于在特定时间点和一组calendar fields例如YEAR ,MONTH ,DAY_OF_MONTH ,HOUR等)之间
* 进行转换的方法,以及用于处理日历字段(例如获取下一星期日期)的方法。时间的瞬间可以用毫秒值表示
* 该值是从1970年1月1日格林尼治标准时间(Gregorian)到Epoch的偏移量。
*
* Calendar提供了一个类方法getInstance ,用于获取这种类型的通常有用的对象。
* Calendar的getInstance方法返回一个Calendar对象,该对象的日历字段已使用当前日期和时间初始化:
* Calendar rightNow = Calendar.getInstance();
*/
public abstract class Calendar implements Serializable, Cloneable, Comparable<Calendar>
public class TestCalendar {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getClass());
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int date = calendar.get(Calendar.DATE);
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
System.out.printf("%d-%d-%d %d:%d:%d 星期%d", year, month, date, hour, minute, second, week);
calendar.set(Calendar.YEAR,2000);
calendar.set(Calendar.MONTH,2);
calendar.set(Calendar.DATE,28);
int year2 = calendar.get(Calendar.YEAR);
int month2 = calendar.get(Calendar.MONTH);
int date2 = calendar.get(Calendar.DATE);
System.out.printf("%d-%d-%d", year2, month2, date2);//原日期会变
}
}
第三代日期类
前两代日期类都有不足的地方,JDK 1.0中包含了一个java.util.Date类,但是它的大多数方法已经在JDK 1.1引入Calendar类之后被弃用了。而Calendar并不比Date好多少。
-
可变性 : 像日期和时间这样的类应该是不可变的。
-
偏移性 : Date中 的年份是从1900开始的,而月份都从0开始。
-
格式化 : 格式化只对Date有用,Calendar则不行。
第三代日期类常见方法:LocalDate(日期)、LocalTime(时间)、LocalDateTime(日期时间)
public class TestDate03 {
public static void main(String[] args) {
//now()-:获取当前的日期,时间,日期+时间
LocalDate date= LocalDate.now(); //获取当前的日期
System.out.println(date);
LocalTime time=LocalTime.now();
System.out.println(time); //获取当前的时间
LocalDateTime dateTime=LocalDateTime.now();//,获取当前日期+时间
System.out.println(dateTime);
//of():设置指定的日期,时间,日期+时间
LocalDate date1=LocalDate.of(2010,5,25);
LocalTime time1=LocalTime.of(10,15,25);
LocalDateTime dateTime1=LocalDateTime.of(date1,time1);
System.out.println(dateTime1);
System.out.println(dateTime.getYear());
System.out.println(dateTime.getMonth());
System.out.println(dateTime.getMonthValue());
System.out.println(dateTime.getDayOfMonth());
System.out.println(dateTime.getDayOfWeek());
System.out.println(dateTime.getHour());
System.out.println(dateTime.getMinute());
System.out.println(dateTime.getSecond());
LocalDateTime localDateTime=dateTime.withYear(1998); //with:设置日期
System.out.println(localDateTime);
System.out.println(dateTime); //原日期不会跟着新日期改动就变化
LocalDateTime plusYears = localDateTime.plusYears(10); //plus:加操作
System.out.println(plusYears);
LocalDateTime minusMonths = localDateTime.minusMonths(6); //minus:减操作
System.out.println(minusMonths);
//API还有很多方法
}
}
还是那句话,具体的详细信息还是要通过源码或者API帮助文档查找,经常用的API用着用着就熟练了,不常用的查看手册!