Java基础2
类-续
final ;
核心类
字符串和编码
s1. equals ( s2) ;
s1. toLowerCase ( ) ;
toUpperCase ( ) ;
equalsIgnoreCase ( ) ;
StringBuilder
StringBuilder sb = new StringBuilder ( 1024 ) ;
for ( int i = 0 ; i < 1000 ; i++ ) {
sb. append ( ',' ) ;
sb. append ( i) ;
}
String s = sb. toString ( ) ;
StringJoiner
import java. util. StringJoiner;
public class Main {
public static void main ( String[ ] args) {
String[ ] names = { "Bob" , "Alice" , "Grace" } ;
var sj = new StringJoiner ( ", " , "Hello " , "!" ) ;
for ( String name : names) {
sj. add ( name) ;
}
System. out. println ( sj. toString ( ) ) ;
}
}
Hello Bob, Alice, Grace!
String[ ] names = { "Bob" , "Alice" , "Grace" } ;
var s = String. join ( ", " , names) ;
包装类型
Integer n = new Integer ( 100 ) ;
Integer n = Integer. valueOf ( 100 ) ;
System. out. println ( Integer. toString ( 100 ) ) ;
System. out. println ( Integer. toString ( 100 , 36 ) ) ;
System. out. println ( Integer. toHexString ( 100 ) ) ;
System. out. println ( Integer. toOctalString ( 100 ) ) ;
System. out. println ( Integer. toBinaryString ( 100 ) ) ;
Boolean t = Boolean. TRUE;
Boolean f = Boolean. FALSE;
int max = Integer. MAX_VALUE;
int min = Integer. MIN_VALUE;
int sizeOfLong = Long. SIZE;
int bytesOfLong = Long. BYTES;
Number num = new Integer ( 999 ) ;
byte b = num. byteValue ( ) ;
int n = num. intValue ( ) ;
long ln = num. longValue ( ) ;
float f = num. floatValue ( ) ;
double d = num. doubleValue ( ) ;
byte x = - 1 ;
byte y = 127 ;
System. out. println ( Byte. toUnsignedInt ( x) ) ;
System. out. println ( Byte. toUnsignedInt ( y) ) ;
JavaBean
public Type getXyz ( )
public void setXyz ( Type value)
public boolean isChild ( )
public void setChild ( boolean value)
枚举类
enum Weekday {
SUN, MON, TUE, WED, THU, FRI, SAT;
}
记录类
public record Point ( int x, int y) { }
record;
public record Point ( int x, int y) {
public Point {
if ( x < 0 || y < 0 ) {
throw new IllegalArgumentException ( ) ;
}
}
}
BigInteger
BigInteger bi = new BigInteger ( "1234567890" ) ;
System. out. println ( bi. pow ( 5 ) ) ;
BigInteger用于表示任意大小的整数;
BigInteger是不变类,并且继承自Number;
将BigInteger转换成基本类型时可使用longValueExact ( ) 等方法保证结果准确。
BigDecimal
BigDecimal bd = new BigDecimal ( "123.4567" ) ;
System. out. println ( bd. multiply ( bd) ) ;
常用工具类
Math:数学计算
Random:生成伪随机数
SecureRandom:生成安全的随机数