柚子快報激活碼778899分享:開發(fā)語言 Java常用類
柚子快報激活碼778899分享:開發(fā)語言 Java常用類
1. 包裝類
1.1. 什么是包裝類
在開發(fā)中,經(jīng)常用到的基本數(shù)據(jù)類型不是對象,但在實際應用中需要將基本數(shù)據(jù)轉(zhuǎn)化成對象,以便于操作。 為了解決這個不足,Java為每個基本數(shù)據(jù)類型設計了一個對應的類,這樣八個和基本數(shù)據(jù)類型對應的類稱為包裝類。位于java.lang包中
1.2. 包裝類的優(yōu)點
某些方法的參數(shù)必須是對象,為了讓基本數(shù)據(jù)類型的數(shù)據(jù)能作為參數(shù),提供包裝類包裝類還可提供更多的功能其他重要的功能:比如可以實現(xiàn)字符串和基本數(shù)據(jù)類型之間的轉(zhuǎn)換
public class TestWrapper1 {
public static void main(String[] args) {
List list = new ArrayList();
list.add(new Integer(56));
System.out.println(list); // [56]
System.out.println(Integer.SIZE); // 32
System.out.println(Integer.MAX_VALUE); // 2147483647
System.out.println(Integer.MIN_VALUE); // -2147483648
System.out.println(Integer.toBinaryString(123)); // 1111011
System.out.println(Integer.toOctalString(123)); // 173
System.out.println(Integer.toHexString(123)); // 7b
String str = "123";
int num = Integer.parseInt(str);
System.out.println(num); // 123
String str2 = "123.45";
double d = Double.parseDouble(str2);
System.out.println(d); // 123.45
}
}
注意:
包裝類的對象需要占用棧內(nèi)存和堆內(nèi)存,而基本數(shù)據(jù)類型變量只占用棧內(nèi)存;基本數(shù)據(jù)類型變量占用空間少,更簡單靈活高效作為成員變量,初始值不同,int 0; Integer null除了Character和Boolean外,其他都是數(shù)字型,數(shù)字型都是java.lang.Number的子類
1.3. 使用包裝類
1.3.1. 自動裝箱和自動拆箱
自動裝箱和拆箱就是將基本數(shù)據(jù)類型和包裝類之間進行自動的相互轉(zhuǎn)換
自動裝箱:基本類型的數(shù)據(jù)處于需要對象的環(huán)境中,會自動轉(zhuǎn)為對象自動拆箱:每當需要一個值時,對象會自動轉(zhuǎn)成基本數(shù)據(jù)類型,沒必要顯示調(diào)用intValue()、doubleValue()等轉(zhuǎn)型方法
自動裝箱過程是通過調(diào)用包裝類的valueOf()方法實現(xiàn)的,自動拆箱過程是通過調(diào)用包裝類的xxxValue()方法實現(xiàn)的(如intValue()、doubleValue())
public class TestWrapper2 {
public static void main(String[] args) {
Integer in = 5;
Integer in2 = new Integer(5);
System.out.println(in == in2); // true
int i = in2;
int i2 = in2.intValue();
System.out.println(i2); // 5
Integer in3 = new Integer(56);
Integer in4 = new Integer(56);
System.out.println(in3 == in4); // false
System.out.println(in3.equals(in4)); // true
Integer in5 = 25;
Integer in6 = 25;
System.out.println(in5 == in6); // true
System.out.println(in5.equals(in6)); // true
Integer in7 = 256;
Integer in8 = 256;
System.out.println(in7 == in8); // false
System.out.println(in7.equals(in8)); // true
}
}
1.3.2. 理解Integer源碼
Integer的父類是Number類;底層就是封裝了一個int類型的value常量,可以通過構造方法、intValue()等賦值取值
public class Integer extends Number{
private final int value;
public Integer(int value) {
this.value = value;
}
@Override
public int intValue() {
return value;
}
}
Integer類提供了一個靜態(tài)內(nèi)部類IntegerCache,對于定義一個靜態(tài)數(shù)組cache,長度為256,賦值為-128-127。對于自動裝箱,如果是-128-127范圍內(nèi)的數(shù)據(jù),直接獲取數(shù)組的指定值;范圍之外的數(shù)據(jù),通過new Integer()重新創(chuàng)建對象。
public class Integer extends Number{
public static class IntegerCache {
static final int low = -128;
static final int high;
static final java.lang.Integer cache[];
static {
int h = 127;
high = h;
cache = new java.lang.Integer[(high - low) + 1];
int j = low;
for (int i = 0; i < cache.length; i++) {
cache[i] = new java.lang.Integer(j++);
}
}
}
public static java.lang.Integer valueOf(int i) {
if(i >= IntegerCache.low && i <= IntegerCache.high) return IntegerCache.cache[i + (-IntegerCache.low)];
return new java.lang.Integer(i);
}
}
注意:
JDK1.5之后,增加了自動裝箱和拆箱功能自動裝箱調(diào)用的是valueOf()方法,而不是new Integer()方法自動拆箱調(diào)用的是xxxValue()方法包裝類在自動裝箱時為了提高效率,對于-128-127之間的值會進行緩存處理。超過范圍,對象之間不能使用==比較,而是使用equals方法
2. String類
字符串相關的類:String類、StringBuilder類、StringBuffer類
String類:代表不可變的字符序列StringBuilder類和StringBuffer類:代表可變字符序列
2.1. String類的使用
public class TestString1 {
public static void main(String[] args) {
String str = "wyb王一博";
System.out.println(str.length()); // 6
System.out.println(str.isEmpty()); // false
System.out.println(str.startsWith("w")); // true
System.out.println(str.endsWith("b")); // true
System.out.println(str.toUpperCase()); // WYB王一博
System.out.println(str.toLowerCase()); // wyb王一博
// str = str.toUpperCase();
// System.out.println(str); // WYB
System.out.println(str.charAt(1)); // y
System.out.println(str.substring(3,6)); // 王一博
System.out.println(str.substring(1)); // yb王一博
System.out.println(str.indexOf("y")); // 1
byte[] bytes = str.getBytes();
System.out.println(bytes.length); // 12
System.out.println(Arrays.toString(bytes)); // [119, 121, 98, -25, -114, -117, -28, -72, -128, -27, -115, -102]
String s = new String(bytes, 1, 2);
System.out.println(s); // yb
System.out.println(str); // wyb王一博
boolean flag = str.contains("wyb");
System.out.println(flag); // true
str = str.concat("xz").concat("肖戰(zhàn)");
System.out.println(str); // wyb王一博xz肖戰(zhàn)
str = str.replace("wyb", "一啵");
System.out.println(str); // 一啵王一博xz肖戰(zhàn)
String s1 = " x z ";
System.out.println(s1.length()); // 6
System.out.println(s1.trim()); // x z
String str1 = "bjyx";
String str2 = "bjyx";
System.out.println(str1 == str2); // true
System.out.println(str1.equals(str2)); // true
String str3 = new String("bjyx");
String str4 = new String("bjyx");
System.out.println(str3 == str4); // false
System.out.println(str3.equals(str4)); // true
String str5 = "";
String str6 = null;
System.out.println(str5.isEmpty()); // true
// System.out.println(str6.isEmpty()); // Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.isEmpty()" because "str6" is null
}
}
方法
charAt(int index):返回指定索引處的char值compareTo(String anotherString):按字典順序比較兩個字符串concat(String str):將指定字符串連接到此字符串的結尾contains(CharSequence s):當且僅當此字符串包含指定char序列時,返回trueendsWith(String suffix):是否以指定的后綴結束,返回booleanstartsWith(String prefix):測試此字符串是否以指定前綴開始,返回booleanstartsWith(String prefix, int toffset):測試此字符串從指定索引開始的子字符串是否以指定前綴開始,返回booleanequals(Object anObject):此字符串與指定的對象比較,返回booleanequalsIgnoreCase(String anotherString):將String與另一個String比較,忽略大小寫,返回booleanhashCode():返回此字符串的哈希碼indexOf(int ch):返回指定字符在此字符串中第一次出現(xiàn)的索引indexOf(int ch, int fromIndex):返回指定字符在此字符串中第一次出現(xiàn)的索引,從指定的索引開始搜索indexOf(String str):返回指定子字符串在此字符串中第一次出現(xiàn)的索引indexOf(String str, int fromIndex):返回指定子字符串在此字符串中第一次出現(xiàn)的索引,從指定索引開始isEmpty():當且僅當length()為0時,返回truelastIndexOf(int ch):返回指定字符在此字符串中最后一次出現(xiàn)的索引值lastIndexOf(int ch, int fromIndex):返回指定字符在此字符串中最后一次出現(xiàn)的索引值,從指定索引處開始進行反向搜索lastIndexOf(String str):返回指定子字符串在此字符串中最右邊出現(xiàn)的索引值length():返回此字符串的長度replace(char oldChar, char newChar):返回一個新的字符串,它是通過用newChar替換此字符串中出現(xiàn)的所有oldChar得到的replace(CharSequence target, CharSequence replacement):使用指定的字面了值替換序列替換此字符串所有匹配字面值目標序列的子字符串replaceAll(String regex, String replacement):使用給定的replacement替換此字符串所有匹配字面值目標序列的子字符串split(String regex):根據(jù)給定正則表達式的匹配拆分字符串substring(int beginIndex):返回一個新的字符串,它是此字符串的一個子字符串substring(int beginIndex, int endIndex):返回一個新的字符串,它是此字符串的一個子字符串toLowerCase():將字符串中所有字符轉(zhuǎn)為小寫toUpperCase():將字符串中所有字符轉(zhuǎn)為大寫toString():返回此對象本身(它已經(jīng)是一個字符串)trim():返回字符串的副本,忽略前導空白和尾部空白
2.2. 理解String類源碼
String類是一個final類,意味著該類不能再有子類String類底層是一個字符數(shù)組value,各種方法的操作其實都是對該數(shù)組的操作
public final class String implements java.io.Serializable, Comparable, CharSequence {
private final char value[];
public String() {
this.value = "".value;
}
public String(java.lang.String original) {
this.value = original.value;
}
public boolean isEmpty() {
return value.length == 0;
}
public int length() {
return value.length;
}
public char charAt(int index) {
if(index < 0 || index >= value.length) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}
public java.lang.String toString() {
return this;
}
}
String類的equals()方法就是比較底層的字符數(shù)組各個元素是否相同,只要發(fā)現(xiàn)一個字符不相同,就返回false。如果所有字符都相同,返回true。如果兩個變量指向了同一個字符數(shù)組,直接返回true
public boolean equals(Object anObject) {
if(this == anObject) return true;
if(anObject instanceof java.lang.String) {
java.lang.String anotherString = (java.lang.String)anObject;
int n = value.length;
if(n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if(v1[i] != v2[i]) return false;
i++;
}
return true;
}
}
return false;
}
String類的concat()是創(chuàng)建一個新的字符數(shù)組,存放原來字符數(shù)組和新加入的字符數(shù)組內(nèi)容,然后以該新數(shù)組創(chuàng)建一個新的字符串
public java.lang.String concat(java.lang.String str) {
int otherLen = str.length();
if(otherLen == 0) return this;
int len = value.length;
char buf[] = Arrays.copyOf(value, len + otherLen);
str.getChars(buf, len);
return new java.lang.String(buf, true);
}
3. StringBuffer和StringBuilder
StringBuffer和StringBuilder均代表可變的字符序列,這兩個類都是抽象類AbstractStringBuilder的子類,方法幾乎一樣
StringBuffer是JSK1.0提供的類,線程安全,做線程同步檢查,效率較低StringBuilder是JDK1.5提供的類,線程不安全,不做線程同步檢查,效率較高,建議采用該類
3.1. 使用StringBuilder類
public class TestStringBuilder {
public static void main(String[] args) {
StringBuilder builder = new StringBuilder("wyb");
builder.append("xz");
System.out.println(builder); // wybxz
builder.insert(3, "bjyx");
System.out.println(builder); // wybbjyxxz
builder.setCharAt(3, 'B');
System.out.println(builder); // wybBjyxxz
builder.replace(3,6, "HHK");
System.out.println(builder); // wybHHKxxz
builder.deleteCharAt(6);
System.out.println(builder); // wybHHKxz
builder.delete(6, builder.length());
System.out.println(builder); // wybHHK
builder.reverse();
System.out.println(builder); // KHHbyw
String string = builder.toString();
System.out.println(string); // KHHbyw
}
}
注意:實際開發(fā)中StringBuilder的使用場合:字符串的拼接(SQL語句)方法
append(boolean b):將boolean參數(shù)的字符串表示形式追加到序列capacity():返回當前容量charAt(int index):返回此序列中指定索引處的char值delete(int start, int end):移除此序列的子字符串中的字符deleteCharAt(int index):移除此序列指定位置上的charensureCapacity(int minimumCapacity):確保容量至少等于指定的最小值indexOf(String str):返回第一次出現(xiàn)的指定字符串在該字符串中的索引indexOf(String str, int fromIndex):從指定的索引處開始,返回第一次出現(xiàn)的指定字符串在該字符串中的索引lastIndexOf(String str):返回最右邊出現(xiàn)的指定字符串在該字符串中的索引lastIndexOf(String str, int fromIndex):從指定的索引處開始,返回最后一次出現(xiàn)的指定字符串在該字符串中的索引insert(int offset, boolean b):將boolean參數(shù)的字符串表示形式插入此序列中l(wèi)ength():返回長度(字符數(shù))replace(int start, int end, String str):使用給定String中的字符替換此序列的子字符串中的字符reverse():將此字符序列用其反轉(zhuǎn)形式取代substring(int start):返回一個新的String,它包含此字符序列當前所包含字符的子序列substring(int start, int end):返回一個新的String,它包含此字符序列當前所包含字符的子序列toString():返回此序列中數(shù)據(jù)的字符串表示形式
3.2. 理解StringBuilder源碼
StringBuilder類底層和String一樣,也是一個字符串數(shù)組value,但不是final的。變量count表示的是底層字符數(shù)組元素的真實個數(shù),不是底層字符數(shù)組的長度默認數(shù)組的長度是16。也可以通過構造方法直接指定初始長度。length()方法返回的字符數(shù)組元素的真實個數(shù),capacity()返回的是底層數(shù)組的長度
public class StringBuilder extends AbstractStringBuilder implements Appendable, java.io.Serializable, Comparable, CharSequence {
char[] value;
int count;
public StringBuilder() {
super(16);
}
public StringBuilder(int capacity) {
super(capacity);
}
public int length() {
return count;
}
public int capacity() {
return value.length;
}
public String toString() {
return new String(value, 0, count);
}
}
每次添加字符串時要擴容,擴容默認策略是增加到原來長度的2倍+2
public AbstractStringBuilder append(String str) {
if (str == null) {
return appendNull();
}
int len = str.length();
ensureCapacityInternal(count + len);
str.getCharts(0, len, value, count);
count += len;
return this;
}
private void ensureCapacityInternal(int minimumCapacity) {
// 如果長度不足,就擴容
int oldCapacity = value.length >> coder;
if (minimumCapacity - oldCapacity > 0) {
value = Arrays.copyOf(value,
newCapacity(minimumCapacity) << coder);
}
}
private int newCapacity(int minCapacity) {
int oldLength = value.length;
int newLength = minCapacity << coder;
int growth = newLength - oldLength;
int length = ArraysSupport.newLength(oldLength, growth, oldLength + (2 << coder));
if (length == Integer.MAX_VALUE) {
throw new OutOfMemoryError("Required length exceeds implementation limit");
}
return length >> coder;
}
4. 日期類
用long類型表示時間,如果想獲得現(xiàn)在時刻的值,可以使用:long now = System.currentTimeMillis();
4.1. Date類
import java.util.Date;
public class TestDate {
public static void main(String[] args) {
Date now = new Date();
System.out.println(now.toString()); // Thu Aug 01 08:40:07 CST 2024
System.out.println(now.toLocaleString()); // 2024年8月1日 08:40:20
System.out.println(now.getYear()); // 124 1900+124=2024
System.out.println(now.getMonth()); // 7 0-11
System.out.println(now.getDate()); // 1
System.out.println(now.getDay()); // 4-星期
System.out.println(now.getHours()); // 8
System.out.println(now.getMinutes()); // 41
System.out.println(now.getSeconds()); // 8
long l = now.getTime();
System.out.println(l); // 1722520811936
System.out.println(System.currentTimeMillis()); // 1722520811967
System.out.println(System.nanoTime()); // 1735948366006333
Date date1 = new Date(-(long)(1000*60*60*24)*31);
System.out.println(date1.toLocaleString()); // 1969年12月1日 08:00:00
java.sql.Date sDate = new java.sql.Date(System.currentTimeMillis());
System.out.println(sDate); // 2024-08-01
java.sql.Date sDate2 = java.sql.Date.valueOf("2024-08-01");
System.out.println(sDate2); // 2024-08-01
}
}
查看API文檔可以看到Date類中很多方法都已經(jīng)過時了。JDK1.1之后,日期操作一般使用Calendar類,而字符串的轉(zhuǎn)化使用DateFormat類
4.2. 理解Date類的源碼
public class Date implements java.io.Serializable, Cloneable, Comparable
private transient long fastTime;
public Date() {
this(System.currentTimeMillis());
}
public Date(long date) {
fastTime = date;
}
public long getTime() {
return getTimeImpl();
}
public final long getTimeImpl() {
if(cdate != null && !cdate.isNormalized()) {
normalize();
}
return fastTime;
}
}
Date類中提供一個成員變量fastTime,表示相應時間對應的毫秒數(shù)
4.3. DateFormat類
DateFormat是一個抽象類,一般使用他的子類SimpleDateFormat類來實現(xiàn)。作用是把時間對象轉(zhuǎn)化成指定格式的字符串,反之,把指定格式的字符串轉(zhuǎn)為時間對象
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDateFormat {
public static void main(String[] args) {
// int age = java.lang.Integer.parseInt("123abc");
// System.out.println(age); // 報錯
String str1 = "1999-12-23";
java.sql.Date date1 = java.sql.Date.valueOf(str1);
System.out.println(date1.toString()); // 1999-12-23
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String str = "1999-12-23 09:23:45";
Date date = null;
try {
date = dateFormat.parse(str);
}catch (ParseException e) {
e.printStackTrace();
}
System.out.println(date.toString()); // Thu Dec 23 09:23:45 CST 1999
System.out.println(date.toLocaleString()); // 1999年12月23日 09:23:45
DateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh時mm分ss秒"); // 1999年12月23日 09時23分45秒
String str2 = sdf.format(date);
System.out.println(str2);
}
}
4.4. Calendar類
Calendar類是一個抽象類,提供了關于日期計算的功能。GregorianCalendar是Calendar類的一個子類,提供了大多數(shù)國家/地區(qū)使用的標準日歷
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class TestCalendar {
public static void main(String[] args) {
Calendar cal = new GregorianCalendar();
System.out.println(cal.get(Calendar.YEAR)); // 2024
System.out.println(cal.get(Calendar.MONTH)); // 7
System.out.println(cal.get(Calendar.DATE)); // 1
System.out.println(cal.get(Calendar.HOUR)); // 10
System.out.println(cal.get(Calendar.MINUTE)); // 22
System.out.println(cal.get(Calendar.SECOND)); // 18
System.out.println(cal.get(Calendar.DAY_OF_WEEK)); // 5
cal.set(Calendar.YEAR, 2000);
int max = cal.getActualMaximum(Calendar.DATE);
System.out.println(max);
for (int i = 1; i <= max; i++) {
System.out.println(cal.get(Calendar.DAY_OF_WEEK)); // 從 2000 年 8 月 1 日開始,依次打印每一天的星期幾,直到 8 月 31 日
cal.add(Calendar.DATE, 1);
}
System.out.println(cal.get(Calendar.DAY_OF_WEEK)); // 6
System.out.println(cal.getActualMinimum(Calendar.DATE)); // 1
Date now = new Date();
cal.setTime(now); // Date -> Calendar
Date now2 = cal.getTime(); // Calendar -> Date
}
}
4.5. 使用Calendar類實現(xiàn)萬年歷
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Scanner;
/**
* 可視化日歷 Calendar
* 可以判斷這個月一共多少天、某一天是星期幾
* 1.實現(xiàn)思路
* 1.按照提示輸入任何一個日期
* 2.打印日歷
* 1.打印日歷頭:日 一 二 三 四 五 六
* 2.打印1日之前的空格(循環(huán))
* 3.打印每一天(循環(huán)),周六換行
* 2.涉及技能點
* 1.字符串轉(zhuǎn)換成Date:DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = sdf.parse(sdate);
* 2.Date轉(zhuǎn)換成Calendar:cal.setTime(sdate);
* 3.把1999-12-23修改為1999-12-1:cal.set(Calendar.DATE,1);
* 4.判斷1999-12-1是星期幾:cal.get(Calendar.DAY_OF_WEEK)
* 5.獲取當前月的最大天數(shù):cal.getActualMaximum(Calendar.DATE)
* 6.如何判斷每天是不是星期六,如果是周六,換行:cal.get(Calendar.DAY_OF_WEEK)==7 cal.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY
* 7.判斷是不是當天,如果是,打印*:cal.get(Calendar.DATE) *
* 8.如何日期增加1天:cal.add(Calendar.DATE, 1);
*/
public class VisualCalendar {
public static void main(String[] args) {
System.out.println("請輸入日期(按照格式:2030-3-10):");
Scanner scanner = new Scanner(System.in);
String temp = scanner.nextLine();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
// 1. 將字符串轉(zhuǎn)為日期
Date date = format.parse(temp);
// 2. 將日期轉(zhuǎn)為日歷
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
// 3. 把日期中的Date取出
int day = calendar.get(Calendar.DATE);
// 4. 將日歷變?yōu)楫斣碌?日
calendar.set(Calendar.DATE, 1);
// 5. 打印日歷頭信息
System.out.println("日\t一\t二\t三\t四\t五\t六");
// 6. 打印1日之前的空格(要知道1日是星期幾)
for (int i = 1; i < calendar.get(Calendar.DAY_OF_WEEK); i++) {
System.out.print("\t");
}
// 7. 獲取當月的最大天數(shù)
int maxDate = calendar.getActualMaximum(Calendar.DATE);
// 8. 打印日歷 1-31/28/30
for (int i = 1; i <= maxDate; i++) {
// 8.1. 如果是當天,打印*
if(i == day) {
System.out.print("*");
}
// 8.2. 打印該天
System.out.print(i + "\t");
// 8.3. 如果是周六,換行
int w = calendar.get(Calendar.DAY_OF_WEEK);
if(w == Calendar.SATURDAY) {
System.out.print("\n");
}
// 8.4. 日歷改為下一天
calendar.add(Calendar.DATE, 1);
}
}catch (ParseException e) {
e.printStackTrace();
}
}
}
柚子快報激活碼778899分享:開發(fā)語言 Java常用類
精彩文章
本文內(nèi)容根據(jù)網(wǎng)絡資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點和立場。
轉(zhuǎn)載請注明,如有侵權,聯(lián)系刪除。