java提供了一系列的工具类,咱们应用的时候能够访问它们的属性和方法,可是工具类不少,记住经常使用的便可!使用的时候就去API帮助文档手册查找,有离线的和在线版本的,离线的百度搜索一下都能找到java
在线官网:https://docs.oracle.com/javase/8/docs/api/git
中文参考官网:https://www.matools.com/api/java8算法
以前咱们说过Object是全部类的根类,那么说具体的工具类以前,咱们先说一下Objectwindows
说白了Object也是一个类,那么确定也有对应的方法api
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作案例来进行讲解,此类掌握了以后其它的包装类大同小异多线程
从上面API帮助文档手册能够看出几个信息,全部的类均可以从 API帮助文档手册上查看!oracle
所属包:Integer类所属java.lang下,使用的时候无需导包app
继承信息: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); } */
能够从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')); //转换为小写 } }
除了从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
仍是简单看一下源码
/** * 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));
/** * 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
/** * 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)); } }
/** * 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());
/** * 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); }
/** * 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还有不少方法 } }
/** * An abstract representation of file and directory pathnames. * * 文件和目录路径名的抽象表示,也就是把文件和文件夹封装成了一个对象,能够用程序操做它 */ public class File implements Serializable, Comparable<File> {
public class TestFile { public static void main(String[] args) throws IOException { /**建立文件对象File * new File(String pathname) 根据路径构建一个File对象 * new File(File parent,String child): 根据父目录文件+子路径构建 * new File(String parent,String child) 根据父目录+子路径构建 */ File file1 = new File("E:\\testA.txt"); //路径分隔符:\\或者/,是Windows系统私有 File file2 = new File("E:\\", "testB.txt"); File parent = new File("E:\\"); File file3 = new File(parent, "testC.txt"); /** * File.separator属性帮咱们获取当前操做系统的路径拼接符号 * windows系统中,默认用"\"做为路径分隔符 * unix和Linux系统中,默认用"/"做为路径分隔符 */ File file = new File("E:" + File.separator + "testD.txt"); //文件经常使用方法 if (file1.exists()) { //exists():判断文件是否存在 file1.delete(); //delete():删除文件 } else { file1.createNewFile(); //createNewFile():建立文件 } System.out.println(file1.canRead()); //文件是否可读 System.out.println(file1.canWrite()); //文件是否可写 System.out.println(file1.getName()); //获取文件名字 System.out.println(file1.getParent()); //获取上一级目录 System.out.println(file1.length()); //获取文件的大小 System.out.println(file1.isDirectory()); //是否目录 System.out.println(file1.isFile()); //是否文件 System.out.println(file1.isHidden()); //是否隐藏 System.out.println(file1.getPath()); //获取相对路径,相对于一个参照物的路径 System.out.println(file1.getAbsolutePath()); //获取绝对路径,文件的完整路径 File way = new File("a/b/c/test.txt"); System.out.println("绝对路径:" + way.getAbsolutePath()); System.out.println("相对路径:" + way.getPath()); //此参照的是当前工做目录 //目录经常使用方法 File path = new File("E:\\a"); if (path.exists()) { path.delete(); //只会删除空的单层目录 } else { path.mkdir(); //只会建立单层目录 } File path2 = new File("E:/a/b/c"); path2.mkdirs(); //能够建立多层目录 //获取 String[] list = path.list(); for (String s : list) { System.out.println(s); } System.out.println("----------------"); for (File listFile : path.listFiles()) { System.out.println(listFile + "," ); } //文件具体数据内容的操做是以io流方式操做 } }
仍是那句话,具体的详细信息仍是要经过源码或者API帮助文档查找,常常用的API用着用着就熟练了,不经常使用的查看手册!