Java常用类 常用类 Object类 Object类的使用:
Object类是所有Java类的根父类。
如果在类的声明中未使用extends关键字指明其父类,则默认父类是java.lang.Object类。
Object类中的功能(属性、方法)具有通用性。
==和equals()方法对比:
==:
基本类型比较值,只要两个变量的值相等,即为true
引用类型比较引用地址(是否指向同一个对象):只有指向同一个对象时,==才返回true
用“==”进行比较时,符号两边的数据类型必须兼容(可自动转换的基本数据类型除外),否则编译出错
equals():
所有类都继承了Object,也就获得了equals()方法。只能比较引用类型,其作用与“==”相同,比较是否指向同一个对象
对类File、String、Date及包装类 (Wrapper Class)来说,是比较类型及内容而不考虑引用的是否是同一个对象,因为在这些类中重写了Object类的equals()方法
当自定义使用equals()时,可以重写。用于比较两个对象的“内容”是否都相等
重写equals方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 public class Test01 { public static void main (String[] args) { Order order1 = new Order (1 ,"手机" ); Order order2 = new Order (1 ,"手机" ); Menu Menu1 = new Menu (1 ,"手机" ); Menu Menu2 = new Menu (1 ,"手机" ); System.out.println(Menu1.getClass()); System.out.println(order1.getClass()); System.out.println(order1.equals(order2)); System.out.println(Menu1.equals(Menu2)); System.out.println(Menu1.equals(order1)); System.out.println(Menu2.equals(order2)); } } class Order { private int orderId; private String orderName; public void setOrderName (String orderName) { this .orderName = orderName; } public String getOrderName () { return orderName; } public int getOrderId () { return orderId; } public void setOrderId (int orderId) { this .orderId = orderId; } public Order (int orderId, String orderName) { this .orderId = orderId; this .orderName = orderName; } @Override public boolean equals (Object obj) { if (this == obj) return true ; if (obj instanceof Order){ Order order = (Order)obj; return this .orderId == order.orderId && this .orderName.equals(order.getOrderName()); } return false ; } } class Menu extends Order { public Menu (int orderId, String orderName) { super (orderId, orderName); } }
toString()方法:
toString()方法在Object类中定义,其返回值是String类型,返回类名和它的引用地址
在打印引用对象时,会自动调用toString()方法
Action action = new Action();
System.out.println(action);
相当于 System.out.println(action.toString());
对类File、String、Date及包装类 (Wrapper Class)来说,其内部重写了Object类的toString()方法
可以根据需要在用户自定义类型中重写toString()方法
重写toString()方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 public class Action { String name; int age; public String getName () { return name; } public void setName (String name) { this .name = name; } public int getAge () { return age; } public void setAge (int age) { this .age = age; } public Action () { } public Action (String name, int age) { this .name = name; this .age = age; } @Override public String toString () { return "Action[name=" +name+", age=" +age+"]" ; } }
JUnit单元测试类 单元测试类的要求:
类必须是public访问权限
此类提供公共的无参构造器
单元测试类中单元测试方法要求:
方法的访问权限是public
没有返回值
没有形参
单元测试方法上需要声明注解@Test
,导入org.junit.Test
;
执行单元测试方法:双击单元测试方法,右击执行
1 2 3 4 5 6 7 8 9 10 11 12 13 import org.junit.Test;public class JUnitTest { int num = 10 ; @Test public void testEquals () { String str1 = new String ("MM" ); String str2 = new String ("MM" ); System.out.println(str1.equals(str2)); System.out.println(num); } }
包装类(Wrapper) 针对八种基本数据类型定义相应的引用类型—包装类(封装类)
有了类的特点,就可以调用类中的方法,Java才是真正的面向对象
基本数据类型、包装类、String类之间的转化:
paraseXxx(String str)、自动装箱和自动拆箱:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 import org.junit.Test;public class WrapperTest { @Test public void test01 () { int num1 = 10 ; Integer integer = new Integer (num1); System.out.println(integer.toString()); Boolean aboolean = new Boolean ("true121" ); Boolean aboolean1 = new Boolean ("TRue" ); System.out.println(aboolean); System.out.println(aboolean1); } @Test public void test02 () { Integer in1 = new Integer (1 ); System.out.println(in1.intValue()+1 ); } @Test public void test03 () { int num1 = 10 ; Integer in1 = num1; boolean b1 = true ; Boolean b2 = b1; int num2 = in1; boolean b3 = b2; } @Test public void test04 () { int num1 = 10 ; String str1 = num1+"" ; float f1 = 12.5F ; String str2 = String.valueOf(f1); Double d1 = new Double (12.3 ); String str3 = d1+"" ; String str4 = String.valueOf(d1); } @Test public void test05 () { String str1 = "123" ; int i1 = Integer.parseInt(str1); int i2 = new Integer (str1); System.out.println(i2); } }
面试题:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import org.junit.Test;public class WrapperTest { @Test public void test06 () { Object o1 = true ? new Integer (1 ) : new Double (2.0 ); System.out.println(o1); Object o2; if (true ) o2 = new Integer (1 ); else o2 = new Double (2.0 ); System.out.println(o2); } }
当你使用三元运算符,两边的操作数的类型不一致的时候,这就涉及到三元操作符的转换规则:
若果两个操作数不可转换,则不做转换,返回值为Object类型
若两个操作数是明确类型的表达式(比如变量),则按照正常的二进制数字来转换。int类型转换为long类型,long类型转换成float类型
若两个操作数中有一个是数字S,另外一个是表达式,且其类型为T,那么,若数字S在T的范围内,则转换为T类型;若S超过了T的范围,则T转换为S类型
若两个操作数字都是直接数字。则返回值类型为范围较大者
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import org.junit.Test;public class WrapperTest { @Test public void test06 () { Integer i = new Integer (1 ); Integer j = new Integer (1 ); System.out.println(i == j); Integer m = 1 ; Integer n = 1 ; System.out.println(m == n); Integer x = 128 ; Integer y = 128 ; System.out.println(x == y); System.out.println(x.equals(y)); } }
原理:Integer内部定义了IntegerCache内部类,IntegerCache中定义了Integer[],保存了从-128-127范围的整数(这个范围的数用的比较频繁)。如果我们使用自动装箱的方式给Integer赋值时,如果在这个范围内,可以直接使用数组中的元素,也就是同一个对象。目的就是为了提高效率。
字符串相关类 String类 String:字符串,使用一对引号引起来表示。
1、String类声明为final,不可被继承
2、String类实现了Serializable接口,表示字符串支持序列化的
3、String类实现了Comparable接口,表示字符串可以比较大小
4、通过字面量的方式(区别于new给一个字符串赋值,此时的字符串值声明在字符串常量池中)
5、字符串常量池中是不会存储相同内容(使用String类的equals()比较,返回true)的字符串的
字符串不可变性的体现:
当对字符串重新赋值时,需要重写指定内存区域赋值,不能使用原有的value进行赋值
当对现的字符串进行连接操作时,也需要重新指定内存区域赋值,不能使用原有的value进行赋值
当调用String的replace()方法修改指定字符或字符串时,也需要重新指定内存区域赋值,不能使用原有的value进行赋值
String实例化的不同方式:
方式一:通过字面量定义的方式
方式二:通过new + 构造器的方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 package _string;import org.junit.Test;public class StringTestJunit { @Test public void test () { String s1 = "javaEE" ; String s2 = "javaEE" ; String s3 = new String ("javaEE" ); String s4 = new String ("javaEE" ); System.out.println(s1 == s2); System.out.println(s1 == s3); System.out.println(s1 == s4); System.out.println(s3 == s4); } }
字符串拼接方式赋值的对比:
常量与常量的拼接结果在常量池。且常量池中不会存在相同内容的常量
只要其中一个是变量,结果就在堆中
如果拼接的结果调用intern()方法,返回值就在常量池中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 package _string;import org.junit.Test;public class StringTestJunit { @Test public void test () { String s1 = "javaEE" ; String s2 = "hadoop" ; String s3 = "javaEEhadoop" ; String s4 = "javaEE" + "hadoop" ; String s5 = s1 + "hadoop" ; String s6 = "javaEE" + s2; String s7 = s1 + s2; System.out.println(s3 == s4); System.out.println(s3 == s5); System.out.println(s3 == s6); System.out.println(s3 == s7); System.out.println(s5 == s6); System.out.println(s5 == s7); System.out.println(s6 == s7); String s8 = s6.intern(); System.out.println(s3 == s8); } }
常用方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 int length () :返回字符串的长度: return value.lengthchar charAt (int index) : 返回某索引处的字符return value[index]boolean isEmpty () :判断是否是空字符串:return value.length == 0 String toLowerCase () :使用默认语言环境,将 String 中的所字符转换为小写 String toUpperCase () :使用默认语言环境,将 String 中的所字符转换为大写 String trim () :返回字符串的副本,忽略前导空白和尾部空白 boolean equals (Object obj) :比较字符串的内容是否相同boolean equalsIgnoreCase (String anotherString) :与equals方法类似,忽略大小写String concat (String str) :将指定字符串连接到此字符串的结尾。 等价于用“+” int compareTo (String anotherString) :比较两个字符串的大小String substring (int beginIndex) :返回一个新的字符串,它是此字符串的从beginIndex开始截取到最后的一个子字符串。 String substring (int beginIndex, int endIndex) :返回一个新字符串,它是此字符串从beginIndex开始截取到endIndex(不包含)的一个子字符串。 boolean endsWith (String suffix) :测试此字符串是否以指定的后缀结束boolean startsWith (String prefix) :测试此字符串是否以指定的前缀开始boolean startsWith (String prefix, int toffset) :测试此字符串从指定索引开始的子字符串是否以指定前缀开始boolean contains (CharSequence s) :当且仅当此字符串包含指定的 char 值序列时,返回 true int indexOf (String str) :返回指定子字符串在此字符串中第一次出现处的索引int indexOf (String str, int fromIndex) :返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始int lastIndexOf (String str) :返回指定子字符串在此字符串中最右边出现处的索引int lastIndexOf (String str, int fromIndex) :返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索注:indexOf和lastIndexOf方法如果未找到都是返回-1 替换: String replace (char oldChar, char newChar) :返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所 oldChar 得到的。 String replace (CharSequence target, CharSequence replacement) :使用指定的字面值替换序列替换此字符串所匹配字面值目标序列的子字符串。 String replaceAll (String regex, String replacement) :使用给定的 replacement 替换此字符串所匹配给定的正则表达式的子字符串。 String replaceFirst (String regex, String replacement) :使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。 匹配: boolean matches (String regex) :告知此字符串是否匹配给定的正则表达式。切片: String[] split(String regex):根据给定正则表达式的匹配拆分此字符串。 String[] split(String regex, int limit):根据匹配给定的正则表达式来拆分此字符串,最多不超过limit个,如果超过了,剩下的全部都放到最后一个元素中。
String与其它结构的转换:
与基本数据类型、包装类之间的转换
String –> 基本数据类型、包装类:调用包装类的静态方法:parseXxx(str)
基本数据类型、包装类 –> String:调用String重载的valueOf(xxx)
与字符数组之间的转换
String –> char[]:调用String的toCharArray()
char[] –> String:调用String的构造器
与字节数组之间的转换
编码:String –> byte[]:调用String的getBytes()
解码:byte[] –> String:调用String的构造器
编码和解码过程可以指定字符集
与StringBuffer、StringBuilder之间的转换
String –>StringBuffer、StringBuilder:调用StringBuffer、StringBuilder构造器
StringBuffer、StringBuilder –>String:①调用String构造器;②StringBuffer、StringBuilder的toString()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 package _string;import org.junit.Test;import java.io.UnsupportedEncodingException;import java.util.Arrays;public class StringTestJunit { @Test public void test1 () { String str="abc123" ; char [] chars = str.toCharArray(); for (int i = 0 ; i < chars.length; i++) { System.out.print(chars[i]+" " ); } char [] ch={'h' ,'e' ,'l' ,'l' ,'o' }; System.out.println(new String (ch)); } @Test public void test2 () throws UnsupportedEncodingException { String str="abc123" ; byte [] bytes = str.getBytes(); System.out.println(Arrays.toString(bytes)); String str1="abc123中国" ; byte [] gbks = str1.getBytes("gbk" ); System.out.println(Arrays.toString(gbks)); byte [] byte1={97 , 98 , 99 , 49 , 50 , 51 }; System.out.println(new String (byte1)); System.out.println(new String (gbks,"gbk" )); } }
String相关算法题:
模拟一个trim方法,去除字符串两端的空格
将字符串中指定部分进行反转
获取一个字符串在另一个字符串中出现的次数
获取两个字符串中最大相同子串
对字符串中字符进行自然顺序排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 package com.atguigu.java;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import org.junit.Test;public class StringExer { public String myTrim (String str) { if (str != null ) { int start = 0 ; int end = str.length() - 1 ; while (start < end && str.charAt(start) == ' ' ) { start++; } while (start < end && str.charAt(end) == ' ' ) { end--; } if (str.charAt(start) == ' ' ) { return "" ; } return str.substring(start, end + 1 ); } return null ; } public String reverse1 (String str, int start, int end) { if (str != null ) { char [] charArray = str.toCharArray(); for (int i = start, j = end; i < j; i++, j--) { char temp = charArray[i]; charArray[i] = charArray[j]; charArray[j] = temp; } return new String (charArray); } return null ; } public String reverse2 (String str, int start, int end) { String newStr = str.substring(0 , start); for (int i = end; i >= start; i--) { newStr += str.charAt(i); } newStr += str.substring(end + 1 ); return newStr; } public String reverse3 (String str, int start, int end) { StringBuffer s = new StringBuffer (str.length()); s.append(str.substring(0 , start)); for (int i = end; i >= start; i--) { s.append(str.charAt(i)); } s.append(str.substring(end + 1 )); return s.toString(); } @Test public void testReverse () { String str = "abcdefg" ; String str1 = reverse3(str, 2 , 5 ); System.out.println(str1); } public int getCount (String mainStr, String subStr) { if (mainStr.length() >= subStr.length()) { int count = 0 ; int index = 0 ; while ((index = mainStr.indexOf(subStr, index)) != -1 ) { index += subStr.length(); count++; } return count; } else { return 0 ; } } @Test public void testGetCount () { String str1 = "cdabkkcadkabkebfkabkskab" ; String str2 = "ab" ; int count = getCount(str1, str2); System.out.println(count); } @Test public void testMyTrim () { String str = " a " ; String newStr = myTrim(str); System.out.println("---" + newStr + "---" ); } public String getMaxSameSubString (String str1, String str2) { if (str1 != null && str2 != null ) { String maxStr = (str1.length() > str2.length()) ? str1 : str2; String minStr = (str1.length() > str2.length()) ? str2 : str1; int len = minStr.length(); for (int i = 0 ; i < len; i++) { for (int x = 0 , y = len - i; y <= len; x++, y++) { if (maxStr.contains(minStr.substring(x, y))) { return minStr.substring(x, y); } } } } return null ; } public String[] getMaxSameSubString1(String str1, String str2) { if (str1 != null && str2 != null ) { StringBuffer sBuffer = new StringBuffer (); String maxString = (str1.length() > str2.length()) ? str1 : str2; String minString = (str1.length() > str2.length()) ? str2 : str1; int len = minString.length(); for (int i = 0 ; i < len; i++) { for (int x = 0 , y = len - i; y <= len; x++, y++) { String subString = minString.substring(x, y); if (maxString.contains(subString)) { sBuffer.append(subString + "," ); } } System.out.println(sBuffer); if (sBuffer.length() != 0 ) { break ; } } String[] split = sBuffer.toString().replaceAll(",$" , "" ).split("\\," ); return split; } return null ; } @Test public void testGetMaxSameSubString () { String str1 = "abcwerthelloyuiodef" ; String str2 = "cvhellobnmiodef" ; String[] strs = getMaxSameSubString1(str1, str2); System.out.println(Arrays.toString(strs)); } @Test public void testSort () { String str = "abcwerthelloyuiodef" ; char [] arr = str.toCharArray(); Arrays.sort(arr); String newStr = new String (arr); System.out.println(newStr); } }
StringBuffer和StringBuilder类 String、StringBuffer、StringBuilder三者的对比:
String:不可变的字符序列;底层使用char[]存储
StringBuffer:可变的字符序列;线程安全的,效率低;底层使用char[]存储
StringBuilder:可变的字符序列;jdk5.0新增的,线程不安全的,效率高;底层使用char[]存储
StringBuffer与StringBuilder的内存解析:
String:
String str = new String(); –> char[] value = new char[0];
String str1 = new String(“abc”); –> char[] value = new char[]{‘a’,’b’,’c’};
StringBuffer:
StringBuffer sb1 = new StringBuffer(); –> char[] value = new char[16];底层创建了一个长度是16的数组。
sb1.append(‘a’); –> value[0] = ‘a’;
sb1.append(‘b’); –> value[1] = ‘b’;
StringBuffer sb2 = new StringBuffer(“abc”); –> char[] value = new char[“abc”.length() + 16];
问题1:System.out.println(sb2.length()); –> 3
问题2:扩容问题:如果要添加的数据底层数组盛不下了,那就需要扩容底层的数组。
默认情况下,扩容为原来容量的2倍 + 2,同时将原数组中的元素复制到新的数组中。
指导意义:开发中建议使用:StringBuffer(int capacity) 或 StringBuilder(int capacity)
常用方法:
1 2 3 4 5 6 7 8 9 10 StringBuffer append (xxx) :提供了很多的append()方法,用于进行字符串拼接 StringBuffer delete (int start,int end) :删除指定位置的内容 StringBuffer replace (int start, int end, String str) :把[start,end)位置替换为str StringBuffer insert (int offset, xxx) :在指定位置插入xxx StringBuffer reverse () :把当前字符序列逆转 public int indexOf (String str) public String substring (int start,int end) public int length () public char charAt (int n ) public void setCharAt (int n ,char ch)
方法链原理:
效率对比: 从高到低排列:StringBuilder > StringBuffer > String
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 package _string;import org.junit.Test;public class StringBufferBuilderTest { @Test public void test () { long startTime = 0L ; long endTime = 0L ; String text = "" ; StringBuffer buffer = new StringBuffer ("" ); StringBuilder builder = new StringBuilder ("" ); startTime = System.currentTimeMillis(); for (int i = 0 ; i < 20000 ; i++) { buffer.append(String.valueOf(i)); } endTime = System.currentTimeMillis(); System.out.println("StringBuffer的执行时间:" + (endTime - startTime)); startTime = System.currentTimeMillis(); for (int i = 0 ; i < 20000 ; i++) { builder.append(String.valueOf(i)); } endTime = System.currentTimeMillis(); System.out.println("StringBuilder的执行时间:" + (endTime - startTime)); startTime = System.currentTimeMillis(); for (int i = 0 ; i < 20000 ; i++) { text = text + i; } endTime = System.currentTimeMillis(); System.out.println("String的执行时间:" + (endTime - startTime)); } }
JDK8之前日期时间API 1、System类中currentTimeMillis()
2、java.util.Date
和子类java.sql.Date
3、SimpleDateFormat类
4、Calender日历类
Date类 java.util.Date类
实例化:
Date()
:使用无参构造器创建的对象可以获取本地当前时间
Date(long date)
常用方法:
getTime()
:返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数
toString()
:打印
java.sql.Date类
实例化:java.sql.Date(new java.util.Date.getTime())
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 package _date;import org.junit.Test;import java.util.Date;public class DateTimeTest { @Test public void test () { long time = System.currentTimeMillis(); System.out.println(time); } @Test public void test2 () { Date date1 = new Date (); System.out.println(date1.toString()); System.out.println(date1.getTime()); Date date2 = new Date (1621220909717L ); System.out.println(date2); java.sql.Date date3 = new java .sql.Date(1621220909717L ); System.out.println(date3); Date date4 = new Date (); java.sql.Date date5 = new java .sql.Date(date4.getTime()); } }
java.text.SimpleDateFormat
类
实例化:
SimpleDateFormat()
:默认的模式和语言环境创建对象
public SimpleDateFormat(String pattern)
:该构造方法可以用参数pattern指定的格式创建一个对象
格式化:public String format(Date date)
:方法格式化时间对象date。
解析:public Date parse(String source)
:从给定字符串的开始解析文本,以生成 一个日期。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 package _date;import org.junit.Test;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class SimpleDateFormatTest { @Test public void test1 () throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat (); Date date = new Date (); String format = sdf.format(date); System.out.println(format); String str="21-5-18 上午10:07" ; Date parse = sdf.parse(str); System.out.println(parse); } @Test public void test2 () throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss" ); String format = sdf.format(new Date ()); System.out.println(format); Date parse = sdf.parse("2021-05-10 19:10:55" ); System.out.println(parse); } @Test public void test3 () throws ParseException { String str="2020-11-20" ; SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd" ); Date parse = sdf.parse(str); java.sql.Date date = new java .sql.Date(parse.getTime()); System.out.println(date); } }
Calender类 java.util.Calendar
(日历)类
Calendar是一个抽象基类,主用用于完成日期字段之间相互操作的功能
实例化:
使用Calendar.getInstance()
方法
调用它的子类GregorianCalendar的构造器
常用方法:
public int get(int field)
public void set(int field, int value)
public void add(int field, int amount)
public final Date getTime()
public final void setTime(Date date)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 package _date;import org.junit.Test;import java.util.Calendar;import java.util.Date;public class CalendarTest { @Test public void test1 () { Calendar calendar = Calendar.getInstance(); System.out.println(calendar.getClass()); int day = calendar.get(Calendar.DAY_OF_MONTH); System.out.println(day); calendar.set(Calendar.DAY_OF_MONTH,22 ); day = calendar.get(Calendar.DAY_OF_MONTH); System.out.println(day); calendar.add(Calendar.DAY_OF_MONTH,-3 ); day = calendar.get(Calendar.DAY_OF_MONTH); System.out.println(day); Date date = calendar.getTime(); System.out.println(date); calendar.setTime(new Date ()); day = calendar.get(Calendar.DAY_OF_MONTH); System.out.println(day); } }
注意:
获取月份时:一月是0,二月是1,以此类推,12月是11
获取星期时:周日是1,周一是2 ,以此类推,周六是7
JDK8中新日期时间API 1、日期时间API的迭代:
第一代:jdk 1.0 Date类
第二代:jdk 1.1 Calendar类,一定程度上替换Date类
第三代:jdk 1.8 提出了新的一套API
2、前两代存在的问题举例:
可变性:像日期和时间这样的类应该是不可变的
偏移性:Date中的年份是从1900开始的,而月份都从0开始
格式化:格式化只对Date用,Calendar则不行
此外,它们也不是线程安全的;不能处理闰秒等
3、java 8 中新的日期时间API涉及到的包
本地日期时间类 本地日期、本地时间、本地日期时间的使用:LocalDate / LocalTime / LocalDateTime。
说明:
它们的实例是不可变的对象
LocalDateTime相较于LocalDate、LocalTime,使用频率要高
类似于Calendar类
常用方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 package _date;import org.junit.Test;import java.time.*;public class JDK8DateTest { @Test public void test () { LocalDate localDate = LocalDate.now(); LocalTime localTime = LocalTime.now(); LocalDateTime localDateTime = LocalDateTime.now(); System.out.println(localDate); System.out.println(localTime); System.out.println(localDateTime); LocalDateTime localDateTime1 = LocalDateTime.of(2021 , 12 , 12 , 12 , 12 , 12 ); System.out.println(localDateTime1); System.out.println(localDateTime.getDayOfMonth()); System.out.println(localDateTime.getDayOfWeek()); System.out.println(localDateTime.getDayOfYear()); System.out.println(localDateTime.getMonthValue()); System.out.println(localDateTime.getHour()); LocalDateTime localDateTime2 = localDateTime.withYear(2000 ); System.out.println(localDateTime2); System.out.println(localDateTime); LocalDateTime localDateTime3 = localDateTime.plusYears(2 ); System.out.println(localDateTime3); System.out.println(localDateTime); LocalDateTime localDateTime4 = localDateTime.minusYears(2 ); System.out.println(localDateTime4); System.out.println(localDateTime); } }
Instant类 Instant:时间线上的一个瞬时点。 概念上讲,它只是简单的表示自1970年1月1日0时0分0秒(UTC开始的秒数)。
说明:类似于 java.util.Date
类
常用方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 package _date;import org.junit.Test;import java.time.Instant;public class JDK8DateTest { @Test public void test () { Instant instant = Instant.now(); System.out.println(instant); OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8 )); System.out.println(offsetDateTime); long milli = instant.toEpochMilli(); System.out.println(milli); Instant instant1 = Instant.ofEpochMilli(1621330026816L ); System.out.println(instant1); } }
java.time.format.DateTimeFormatter
类用于格式化与解析日期或时间。
三种格式化方法:
预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
本地化相关的格式。如:ofLocalizedDateTime(FormatStyle.LONG)
自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)
常用方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 package _date;import org.junit.Test;import java.time.*;import java.time.format.DateTimeFormatter;import java.time.format.FormatStyle;import java.time.temporal.TemporalAccessor;public class JDK8DateTest { @Test public void test () { DateTimeFormatter formatter=DateTimeFormatter.ISO_LOCAL_DATE_TIME; LocalDateTime localDateTime = LocalDateTime.now(); String dateStr1 = formatter.format(localDateTime); System.out.println(localDateTime); System.out.println(dateStr1); String str="2021-05-18T19:38:29.095" ; TemporalAccessor parse = formatter.parse(str); System.out.println(parse); DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG); String dateStr2 = formatter1.format(localDateTime); System.out.println(dateStr2); DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM); String dateStr3 = formatter2.format(LocalDate.now()); System.out.println(dateStr3); DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss" ); String dateStr4 = formatter3.format(localDateTime); System.out.println(dateStr4); TemporalAccessor parse1 = formatter3.parse("2021-05-18 07:45:53" ); System.out.println(parse1); } }
其他API
Java比较器 Java中的对象,正常情况下,只能进行比较:== 或 != 。不能使用 > 或 < 比较对象,但是在开发场景中,我们需要对多个对象进行排序,言外之意,就需要比较对象的大小。 如何实现:使用两个接口中的任何一个:Comparable 或 Comparator。
Comparable接口 Comparable接口强行对实现它的每个类的对象进行整体排序。这种排序被称 为类的自然排序。
说明:
像String、包装类等实现了Comparable接口,重写了compareTo(obj)方法,给出了比较两个对象大小的方式
像String、包装类重写compareTo()方法以后,进行了从小到大的排列
重写compareTo(obj)的规则:
如果当前对象this大于形参对象obj,则返回正整数
如果当前对象this小于形参对象obj,则返回负整数
如果当前对象this等于形参对象obj,则返回零
对于自定义类来说,如果需要排序,我们可以让自定义类实现Comparable接口,重写compareTo(obj)
方法。在compareTo(obj)方法中指明如何排序
实现Comparable接口的对象列表(和数组)可以通过Collections.sort
或Arrays.sort
进行自动排序。实现此接口的对象可以用作有序映射中的键或有 序集合中的元素,无需指定比较器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 package _compare;public class Goods implements Comparable { private String brand; private int price; public Goods () { } public Goods (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; } @Override public String toString () { return "Goods{" + "brand='" + brand + '\'' + ", price=" + price + '}' ; } @Override public int compareTo (Object o) { if (o instanceof Goods){ Goods goods=(Goods)o; if (this .price>goods.price) return 1 ; else if (this .price<goods.price) return -1 ; else return this .brand.compareTo(goods.brand); } throw new RuntimeException ("输入数据类型不一致" ); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 package _compare;import org.junit.Test;import java.util.Arrays;import java.util.Comparator;public class CompareTest { @Test public void test () { Goods[] all = new Goods [5 ]; all[0 ] = new Goods ("《红楼梦》" , 100 ); all[1 ] = new Goods ("《西游记》" , 80 ); all[2 ] = new Goods ("《三国演义》" , 140 ); all[3 ] = new Goods ("《水浒传》" , 120 ); all[4 ] = new Goods ("《Java》" , 100 ); Arrays.sort(all); System.out.println(Arrays.toString(all)); } }
Comparator接口 当元素的类型没实现java.lang.Comparable
接口而又不方便修改代码,或者实现了java.lang.Comparable
接口的排序规则不适合当前的操作,那么可以考虑使用 Comparator 的对象来排序。
说明:
重写compare(Object o1,Object o2)
方法,比较o1和o2的大小:
如果方法返回正整数,则表示o1大于o2
返回负整数,表示o1小于o2
如果返回0,表示相等
可以将Comparator传递给sort方法(如 Collections.sort 或 Arrays.sort),从而允许在排序顺序上实现精确控制
还可以使用Comparator来控制某些数据结构(如有序 set或有序映射)的顺序,或者为那些没有自然顺序的对象collection提供排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 package _compare;public class Goods { private String brand; private int price; public Goods () { } public Goods (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; } @Override public String toString () { return "Goods{" + "brand='" + brand + '\'' + ", price=" + price + '}' ; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 package _compare;import org.junit.Test;import java.util.Arrays;import java.util.Comparator;public class CompareTest { @Test public void test1 () { Goods[] all = new Goods [5 ]; all[0 ] = new Goods ("《红楼梦》" , 100 ); all[1 ] = new Goods ("《西游记》" , 80 ); all[2 ] = new Goods ("《三国演义》" , 140 ); all[3 ] = new Goods ("《水浒传》" , 120 ); all[4 ] = new Goods ("《红楼梦》" , 200 ); Arrays.sort(all, new Comparator <Goods>() { @Override public int compare (Goods o1, Goods o2) { if (o1.getBrand().equals(o2.getBrand())){ return Integer.compare(o1.getPrice(),o2.getPrice()); } return -o1.getBrand().compareTo(o2.getBrand()); } }); System.out.println(Arrays.toString(all)); } }
两种比较器对比:
Comparable接口的方式一旦确定,保证Comparable接口实现类的对象在任何位置都可以比较大小
Comparator接口属于临时性的比较
其他常用类 System类 System类代表系统,系统级的很多属性和控制方法都放置在该类的内部。该类位于java.lang
包。
由于该类的构造器是private的,所以无法创建该类的对象,也就是无法实例化该类。其内部的成员变量和成员方法都是static的,所以也可以很方便的进行调用。
System类内部包含in、out和err三个成员变量,分别代表标准输入流 (键盘输入),标准输出流(显示器)和标准错误输出流(显示器)。
方法:
native long currentTimeMillis()
:返回当前的计算机时间
void exit(int status)
:退出程序,其中status的值为0代表正常退出,非零代表异常退出
void gc()
:请求系统进行垃圾回收
String getProperty(String key)
:获得系统中属性名为key的属性对应的值
Math类 java.lang.Math
提供了一系列静态方法用于科学计算。其方法的参数和返回值类型一般为double型。
常用方法:
BigInteger和BigDecimal类 BigInteger可以表示不可变的任意精度的整数。
BigInteger提供所有 Java 的基本整数操作符的对应物,并提供 java.lang.Math
的所有相关方法。
另外,BigInteger 还提供以下运算:模算术、GCD 计算、质数测试、素数生成、 位操作以及一些其他操作
构造器:BigInteger(String val)
:根据字符串构建BigInteger对象
常用方法:
商业计算中, 要求数字精度比较高,故用到java.math.BigDecimal
类。
BigDecimal类支持不可变的、任意精度的有符号十进制定点数。
构造器:
public BigDecimal(double val)
public BigDecimal(String val)
常用方法:
Arrays类 Arrays类提供了很多操作数组的方法,定义在java.util
包下。
常用方法:
boolean equals(int[] a,int[] b)
:判断两个数组是否相等
String toString(int[] a)
:输出数组信息
void fill(int[] a,int val)
:将指定值填充到数组之中
void sort(int[] a)
:对数组进行排序
int binarySearch(int[] a,int key)
:二分查找
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 package other;import org.junit.Test;import java.math.BigDecimal;import java.math.BigInteger;import java.util.Arrays;public class OtherClassTest { @Test public void test () { long millis = System.currentTimeMillis(); System.out.println(millis); System.out.println(System.getProperty("java.version" )); System.out.println(System.getProperty("java.home" )); System.out.println(System.getProperty("os.name" )); System.out.println(System.getProperty("os.version" )); System.out.println(System.getProperty("user.name" )); System.out.println(System.getProperty("user.home" )); System.out.println(System.getProperty("user.dir" )); System.gc(); System.exit(0 ); } @Test public void test1 () { int a=-1 ; System.out.println(Math.abs(a)); System.out.println(Math.exp(2 )); System.out.println(Math.max(12.1 , 13.5 )); System.out.println(Math.min(12.1 , 13.5 )); System.out.println(Math.random()); System.out.println(Math.round(12.5 )); } @Test public void test2 () { BigInteger bi = new BigInteger ("1243324112311111111111111" ); System.out.println(bi); BigDecimal bd = new BigDecimal ("12435.3511111111111" ); BigDecimal bd2 = new BigDecimal ("11" ); System.out.println(bd.divide(bd2, BigDecimal.ROUND_HALF_UP)); System.out.println(bd.divide(bd2, 25 , BigDecimal.ROUND_HALF_UP)); } @Test public void test3 () { int [] arr1={1 ,2 ,3 ,4 }; int [] arr2={1 ,3 ,2 ,4 }; boolean equals = Arrays.equals(arr1, arr2); System.out.println(equals); System.out.println(Arrays.toString(arr2)); Arrays.fill(arr2,10 ); System.out.println(Arrays.toString(arr2)); int [] arr3=new int []{12 ,13 ,16 ,200 ,356 ,1000 ,1989 }; Arrays.sort(arr3); System.out.println(Arrays.toString(arr3)); System.out.println(Arrays.binarySearch(arr3, 356 )); } }