有没有专门做网站的哪里可以免费设计装修房子
第七章:Java常用类
7.1:字符串相关的类
-  
String的特性
-  
String表示是字符串,使用一对""引起来表示。 -  
String声明为final的,不可被继承。 -  
String实现了Serializable、Comparable接口,表示字符是支持序列化和比较大小。 -  
String内部定义了final char[] value用于存储字符串数据。 -  
String代表不可变的字符串序列。简称:不可变性。 -  
通过字面量的方式(区别于
new)给一个字符串赋值,此时的字符串值声明在字符串常量池中。 -  
字符串常量池中是不会存储相同内容的字符串的。
 -  
通过
new String()的方式创建一个字符串,是数据在堆空间中开辟空间以后对应的地址值。//字面量的定义方式 String s1 = "abc"; String s2 = "abc"; System.out.println(s1 == s2); //trueString s3 = "abc"; s3 += "def"; System.out.println(s3); //abcdef System.out.println(s2); //abc -  
常量与常量的拼接结果在常量池。
 -  
只要其中有一个是变量,结果就在堆中。
 -  
如果拼接的结果调用
intern()方法,返回值就在常量池中。String s1 = "javaEE"; String s2 = "hadoop"; String s3 = "javaEEhadoop";String s4 = "javaEE" + "hadoop"; String s5 = s1 + "hadoop";System.out.println(s3 == s4);//true System.out.println(s3 == s5);//falseString s6 = s5.intern(); System.out.println(s3 == s6);//true 
 -  
 -  
字符串常用方法
-  
int length():返回字符串的长度。 -  
char cahrAt(int index):返回某索引出的字符。 -  
boolean isEmpty():判断是否是空字符串。 -  
String toLowerCase():使用默认语言环境,将String中的所有字符转换为小写。 -  
String toUpperCase():使用默认语言环境,将String中的所有字符转换为大写。 -  
String trim():返回字符串的副本,忽略前导空白和尾部空白。String s1 = "HelloWorld"; System.out.println(s1.length()); //10 System.out.println(s1.charAt(9)); //d System.out.println(s1.isEmpty()); // falseString s2 = s1.toLowerCase(); System.out.println(s2); //helloworldString s3 = " he llo world "; String s4 = s3.trim(); System.out.println("-----" + s4 + "-----"); //----he llo world---- -  
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(不包含)的一个字符串String s1 = "HelloWorld"; String s2 = "helloworld"; System.out.println(s1.equals(s2)); // false System.out.println(s1.equalsIgnoreCase(s2)); // trueString s3 = "abc"; String s4 = s3.concat("def"); System.out.println(s4); //abcdefString s5 = "abc"; String s6 = new String("abe"); System.out.println(s5.compareTo(s6)); //-2String s7 = "小王同学要加油"; String s8 = s7.substring(2); System.out.println(s8); //同学要加油 String s9 = s7.substring(2, 5); System.out.println(s9); //同学要 -  
boolean endsWith(String suffix):测试此字符串是否以指定的后缀结束。 -  
boolean startsWith(String prefix):测试此字符串是否以指定的前缀开始。 -  
boolean startWith(String prefix, int toffset):测试此字符串从指定索引开始的字符串是否以指定前缀开始String str1 = "hellowworld"; boolean b1 = str1.endsWith("rld"); System.out.println(b1); //trueboolean b2 = str1.startsWith("He"); System.out.println(b2); //falseboolean b3 = str1.startsWith("ll",2); System.out.println(b3); //true -  
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):返回指定字符串在此字符串中最后一次出现的索引,从指定的索引开始反向搜索。
String str1 = "hellowworld"; String str2 = "wor"; System.out.println(str1.contains(str2)); //true System.out.println(str1.indexOf("lol")); //-1(表示没有找到) System.out.println(str1.indexOf("lo",5)); //-1String str3 = "hellorworld"; System.out.println(str3.lastIndexOf("or")); //6 System.out.println(str3.lastIndexOf("or",6)); //6 -  
String replace(char oldChar, char newChar):返回一个新的字符串,它是通过newChar替换此字符串中出现的所有orlChar得到的。 -  
String replace(CharSequence target, CharSequence reqlacement):使用指定的字面值替换序列替换此字符串所有匹配字面值目标序列的字符串。 -  
String replaceAll(String regex, String replacement):使用给定的reqlacement替换此字符串所有匹配给定的正则表达式的字符串。 -  
String replaceFirst(String regex, String replacement):使用给定的replacement替换此字符串匹配给定的正则表达式的第一个字符串。String str1 = "小王同学要加油小王"; String str2 = str1.replace('王', '胡'); System.out.println(str2); //小胡同学要加油小胡String str3 = str1.replace("小王", "小胡"); System.out.println(str3); //小胡同学要加油小胡String str = "12hello34world5java7891mysql456"; String string = str.replaceAll("\\d+", ",").replaceAll("^,|,$", ""); System.out.println(string); //hello,world,java,mysql -  
boolean matches(String regex):告知此字符串是否匹配给定的正则表达式。 -  
String[] split(String regex):根据给定正则表达式的匹配拆分此字符串 -  
String[] split(String regex, int limit):根据匹配给定的正则表达式来拆分此字符串,最多不超过limit个,如果超过了,剩下的全部都放到最后一个元素中String str = "12345"; boolean matches = str.matches("\\d+"); System.out.println(matches); //truestr = "hello|world|java"; String[] strs = str.split("\\|"); for (int i = 0; i < strs.length; i++) {System.out.print(strs[i] + "\t"); //hello world java } 
 -  
 -  
String与基本数据类型转换-  
字符串 ———— 基本数据类型、包装类
String str1 = "123"; // 字符串 转 基本数据类型、包装类 int num = Integer.parseInt(str1); // 基本数据类型、包装类 转 字符串 String str2 = String.valueOf(num); -  
字符数组 ———— 字符串
String str1 = "abc123"; // 字符串 转 字符数组 char[] charArray = str1.toCharArray(); // 字符数组 转 字符串 char[] arr = new char[]{'h','e','l','l','o'}; String str2 = new String(arr); -  
字节数组 ———— 字符串
String str1 = "abc123中国"; // 字符串 转 字节数组 byte[] bytes = str1.getBytes(); //使用默认字符集将字符串转字节数组 byte[] gbks = str1.getBytes("gbk"); //使用gbk格式的字符集将字符串转字符数组,此处会有异常 // 字符数组 转 字符串 String str2 = new String(bytes);//使用默认字符集将字符数组转字节串 String str4 = new String(gbks, "gbk");//使用gbk格式的字符集将字符数组转字符串 
 -  
 -  
StringBuffer和StringBuilder类-  
StringBuffer、StringBuilder代表可变的字符序列,可以对字符串内容进行增删,此时不会产生新的对象。 -  
StringBuffer、StringBuilder底层使用char[]存储。 -  
StringBuffer是JDK 1.0中声明的,是线程安全的可变字符序列。 -  
StringBuilder是JDK 5.0中声明的,是线程不安全的可变字符序列。 -  
StringBuffer、StringBuilder使用空参构造器时,底层创建了一个长度是16的数组。public StringBuffer() {super(16); } -  
如果要添加的数据底层数组盛不下了,那就需要扩容底层的数组。默认情况下,扩容为原来容量的2倍+2,同时将原有数组中的元素复制到新数组中。
// StringBuffer类的append方法 public synchronized StringBuffer append(String str) {toStringCache = null;super.append(str);return this; } // StringBuffer类父类AbstractStringBuilder类的append方法 public AbstractStringBuilder append(String str) {if (str == null)return appendNull();int len = str.length();ensureCapacityInternal(count + len);str.getChars(0, len, value, count);count += len;return this; } // AbstractStringBuilder类的ensureCapacityInternal方法 private void ensureCapacityInternal(int minimumCapacity) {if (minimumCapacity - value.length > 0) {value = Arrays.copyOf(value, newCapacity(minimumCapacity));} } // AbstractStringBuilder类的newCapacity方法 private int newCapacity(int minCapacity) {int newCapacity = (value.length << 1) + 2;if (newCapacity - minCapacity < 0) {newCapacity = minCapacity;}return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)? hugeCapacity(minCapacity): newCapacity; } -  
开发中建议使用
StringBuffer(int capacity)或StringBuilder(int capacity)指定数组的长度。 
 -  
 -  
StringBuffer和StringBulider常用方法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():把当前字符序列逆转。
 
7.2:JDK8之前日期时间API
-  
java.lang.System类-  
public static long currentTimeMillis():返回当前时间与1970年1月1日0时之间以毫秒为单位的时间差。long time = System.currentTimeMillis(); System.out.println(time); 
 -  
 -  
java.util.Date类- 构造器 
Date():使用无参构造器创建的对象可以获取本地当前时间。Date(long date):创建指定毫秒数的Date对象。
 - 方法 
toString():显示当前的年、月、日、时、分、秒。getTime():获取当前Date对象对应的毫秒数
 
//构造器一:Date():创建一个对应当前时间的Date对象 Date date1 = new Date(); System.out.println(date1.toString()); System.out.println(date1.getTime()); //构造器二:创建指定毫秒数的Date对象 Date date2 = new Date(155030620410L); System.out.println(date2.toString()); // 将java.util.Date对象转换为java.sql.Date对象 Date date6 = new Date(); java.sql.Date date7 = new java.sql.Date(date6.getTime()); - 构造器 
 -  
java.text.SimpleDateFormat类
Date类的API不易于国际化,大部分被废弃了。java.text.SimpleDateFormat类是一个不与语言环境有关的方式来格式化和解析日期的具体类。-  
构造器
SimpleDateFormat():默认的模式和语言环境创建对象。SimpleDateFormat(String pattern):该构造方法可以用参数pattern指定的格式创建对象
 -  
格式化
public String format(Date date):格式化时间对象date。
 -  
解析
public Date parse(String source):给定字符串的开始解析文本,以生成一个日期。
 -  
按照指定的方式格式化和解析

 
//实例化SimpleDateFormat:使用默认的构造器 SimpleDateFormat sdf = new SimpleDateFormat(); //格式化:日期 --->字符串 Date date = new Date(); String format = sdf.format(date); System.out.println(format); //解析:格式化的逆过程,字符串 ---> 日期 //要求字符串必须是符合SimpleDateFormat识别的格式(通过构造器参数体现)。否则,抛异常。 String str = "22-12-18 上午11:43"; Date date1 = sdf.parse(str); System.out.println(date1); //按照指定的方式格式化和解析:调用带参的构造器 SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); //格式化 String format1 = sdf1.format(date); System.out.println(format1); //解析 Date date2 = sdf1.parse("2020-02-18 11:48:27"); System.out.println(date2); -  
 -  
java.util.Calendar(日历)类Calendar是一个抽象基类,主用用于完成日期字段之间相互操作的功能。- 获取
Calendar实例- 使用
Calendar.getInstance()方法。 - 调用它的子类
GregorianCalendar的构造器。 
 - 使用
 - 常用方法 
public int get(int field):获取想要的时间信息。public void set(int field, int amount):设置想要的时间信息。public void add(int field, int amount):在现在的时间增加到想要的时间。public final Date getTime():日期转为时间。public final void setTime(Date date):时间转为日期。
 - 注意 
- 获取月份时:一月是0,二月是1,以此类推,12月是11。
 - 获取星期时:周日是1,周二是2,以此类推,周六是7。
 
 
//实例化 Calendar calendar = Calendar.getInstance();//get() int days = calendar.get(Calendar.DAY_OF_MONTH); System.out.println(days);//set() calendar.set(Calendar.DAY_OF_MONTH,22); days = calendar.get(Calendar.DAY_OF_MONTH); System.out.println(days);//add() calendar.add(Calendar.DAY_OF_MONTH,-3); days = calendar.get(Calendar.DAY_OF_MONTH); System.out.println(days);//getTime():日历类---> Date Date date = calendar.getTime(); System.out.println(date);//setTime():Date ---> 日历类 Date date1 = new Date(); calendar.setTime(date1); days = calendar.get(Calendar.DAY_OF_MONTH); System.out.println(days); 
7.3:JDK8中新日期时间API
-  
LocalDate、LocalTime、LocalDateTime类LocalDate、LocalTime、LocalDateTime类的实例对象是不可变对象。-  
LocalDate代表IOS格式(yyyy-MM-dd)的日期,可以存储生日、纪念日等日期。 -  
LocalTime表示一个时间,而不是日期。 -  
LocalDateTime是用来表示日期和时间的。 -  
相关方法

 
//now():获取当前的日期、时间、日期+时间 LocalDate localDate = LocalDate.now(); LocalTime localTime = LocalTime.now(); LocalDateTime localDateTime = LocalDateTime.now();System.out.println(localDate); System.out.println(localTime); System.out.println(localDateTime); //of():设置指定的年、月、日、时、分、秒。没有偏移量 LocalDateTime localDateTime1 = LocalDateTime.of(2020, 10, 6, 13, 23, 43); System.out.println(localDateTime1); //getXxx():获取相关的属性 System.out.println(localDateTime.getDayOfMonth()); System.out.println(localDateTime.getDayOfWeek()); System.out.println(localDateTime.getMonth()); System.out.println(localDateTime.getMonthValue()); System.out.println(localDateTime.getMinute()); //体现不可变性 //withXxx():设置相关的属性 LocalDate localDate1 = localDate.withDayOfMonth(22); System.out.println(localDate); System.out.println(localDate1);LocalDateTime localDateTime2 = localDateTime.withHour(4); System.out.println(localDateTime2); //plusXxx():增加相关属性 LocalDateTime localDateTime3 = localDateTime.plusMonths(3); System.out.println(localDateTime3); //minuXxx():减少相关属性 LocalDateTime localDateTime4 = localDateTime.minusDays(6); System.out.println(localDateTime4); -  
 -  
瞬时
Instant-  
Instant时间线上的一个瞬时点。这可能被用来记录应用程序中的事件时间戳。 -  
时间线中的一个点表示一个很大的数,这有利于计算机处理。在
java中,也是从1970年开始,但以毫秒为单位 -  
因为
java.time包是基于纳秒计算的,所以Instant的精度可以达到纳秒级。 -  
1秒 = 1000毫秒 = 10−6^{-6}−6微秒 = 10−910^{-9}10−9纳秒
 -  
相关方法

 
//now() Instant instant = Instant.now(); System.out.println(instant); //添加时间的偏移量 OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8)); System.out.println(offsetDateTime); //toEpochMilli() long milli = instant.toEpochMilli(); System.out.println(milli); //ofEpochMilli() Instant instant1 = Instant.ofEpochMilli(1550475314878L); System.out.println(instant1); -  
 -  
格式化与解析日期或时间
java.time.format.DateTimeFormatter类:该类提供了三种格式化方法-  
预定义的标准格式:
ISO_LOCAL_DATE_TIME、ISO_LOCAL_DATE、ISO_LOCAL_TIME -  
本地化相关格式:
ofLocalizedDateTime()、ofLocalizedDate() -  
自定义格式
 -  
相关方法

 
// 方式一:预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME; //格式化:日期-->字符串 LocalDateTime localDateTime = LocalDateTime.now(); String str1 = formatter.format(localDateTime); System.out.println(str1); //解析:字符串 -->日期 TemporalAccessor parse = formatter.parse("2019-02-18T15:42:18.797"); System.out.println(parse);//方式二: //FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT :适用于LocalDateTime DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG); //格式化 String str2 = formatter1.format(localDateTime); System.out.println(str2); //FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT : 适用于LocalDate DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM); //格式化 String str3 = formatter2.format(LocalDate.now()); System.out.println(str3);//2019-2-18//方式三:自定义的格式 DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); //格式化 String str4 = formatter3.format(LocalDateTime.now()); System.out.println(str4); //解析 TemporalAccessor accessor = formatter3.parse("2019-02-18 03:52:09"); System.out.println(accessor); -  
 -  
其他
API-  
Zoneld:该类中包含了所有的时区信息,一个时区的ID。 -  
ZonedDateTime:一个在ISO-8601日历系统时区的日期时间。 -  
Clock:使用时区提供对当前即时、日期和时间的访问的时钟。 -  
Duration:持续时间,用于计算两个时间间隔。 -  
Period:日期间隔,用于计算两个日期间隔。 -  
TemporalAdjuster:时间校正器。 -  
TemporalAdjusters该类通过静态方法
firstDayOfXxx()/lastDayOfXxx()/nextXxx()提供了大量的常用TemporalAdjuster的实现。 
 -  
 -  
与传统日期处理的转换

 
7.4:java比较器
在Java中经常会设计到对象数组的排序问题,那么就涉及到对象之间的比较问题。
-  
自然排序:
java.lang.ComparableComparable接口强行对实现它的每个类的对象进行整体排序。这种排序被称为类的自然排序。- 实现
Comparable的类必须实现compareTo(Object obj)方法,两个对象即通过compareTo()方法的返回值来比较大小。- 如果当前对象
this大于形参对象obj,则返回正整数。 - 如果当前对象
this小于形参对象obj,则返回负整数。 - 如果当前对象
this等于形参对象obj,则返回0。 
 - 如果当前对象
 Comparable默认都是从小到大排列的。
 -  
定制排序:
java.util.Comparator- 当元素的类型没有实现
java.lang.Comparable接口而又不方便修改代码,或者实现java.lang.Comparable接口的排序规则不适合当前的操作。那么可以考虑使用Comparator的对象来排序,强行对多个对象进行整体排序的比较 - 重写
compare(Object o1, Object o2)方法比较o1和o2的大小。- 如果方法返回正整数,则表示
o1大于o1。 - 如果方法返回0,则表示相等。
 - 如果方法返回负整数,则表示
o1小于o2。 
 - 如果方法返回正整数,则表示
 
 - 当元素的类型没有实现
 -  
自然排序和定值排序的对比
-  
Comparable接口的方式一旦一定,保证Comparable接口实现类的对象在任何位置都可以比较大小。 -  
Comparator接口属于临时性的比较。 
 -  
 
7.5:System类
 System类代表系统,系统级的很多属性和控制方法都防止在该类的内部。该类位于java.lang包。
 由于该类的构造器是private的,所以无法创建该类的对象,也就是无法实例化该类。其内部成员变量和成员方法都是static的,所以也可以很方便的进行调用。
- 成员变量 
in:标准输入流(键盘输入)。out:标准输出流(显示器)。orr:标准错误输出流(显示器)。
 - 成员方法 
native long currentTimeMillis():返回当前计算机时间和1970年1月1日0时所差的毫秒数。void exit(int status):退出程序。其中status的值为0代表正常退出,非零代表异常退出。void gc():是请求系统进行垃圾回收。String getProperty(String key):获取系统中属性名为key的属性对应的值。java.version:java运行时环境版本。java.home:java安装目录。os.name:操作系统的名称。os.version:操作系统的版本。user.name:用户的账户名称。user.home:用户的主目录。user.dir:用户的当前工作目录。
 
7.6:Math类
java.lang.Math提供了一系列静态方法用于科学计算。其方法的参数和返回值类型一般为double型。
abs:绝对值acos、asin、atan、cos、sin、tan:三角函数sqrt:平方根pow(double a, double b):a的b次幂log:自然对数exp:e为底指数max(double a, double b):两个数中找较大的数min(double a, double b):两个数中找较小的数random():返回0.0到1.0的随机数long round(double a):doubel型数据a转换为long型。(四舍五入)toDegrees(double angrad):弧度转角度toRadians(double angdeg):角度转弧度
7.7:BigInteger和BigDecimal
BigInteger类java.math包的BigInteger可以表示不可变的任意精度的整数。BigInteger提供所有java基本整数操作符的对应物,并提供java.lang.Math的所有相关方法。BigInteger还提供模算术、GCD计算、质数测试、素数生成、位操作以及一些其他操作。- 构造器 
BigInteger(String val):根据字符串构建BigInteger对象。
 - 常用方法 
public BigInteger abs():返回此BigInteger的绝对值的BigInteger。BigInteger add(BigInteger val):返回其值为this + val的BigInteger。BigInteger subtract(BigInteger val):返回其值为this - val的BigInteger。BigInteger multiply(BigInteger val):返回其值为this * val的BigInteger。BigInteger divide(BigInteger val):返回其值为this / val的BigInteger。整数相除只保留整数部分。BigInteger remainder(BigInteger val):返回其值为this % val的BigInteger。BigInteger[] divideAndRemainder(BigInteger val):返回包含this / val后跟this % val的两个BigInteger的数组。BigInteger pow(int exponent):返回其值为this 的 exponent次幂的BigInteger。
 
BigDecimal类- 一般的
Float类和Double类可以用来做科学计算或工程计算,但是在商业计算中,要求数字精度比较高,故用到java.math.BigDecimal类。 BigDecimal类支持不可变的、任意精度的有符号十进制定点数。- 构造器 
public BigDecimal(double val)public BigDecimal(String val)
 - 常用方法 
public BigDecimal add(BigDecimal augend)public BigDecimal subtract(BigDecimal subtrahend)public BigDecimal multiply(BigDecimal multiplicand)public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode)
 
- 一般的
 
