一、String
public finall class String implements java.io.Serializable,Comparable<String>,CharSequence{
private final char value[];//存数据的
}
// 所以 String不可被继承
字符串是常量,字符内容存在value[]中,支持序列化,可比较大小。
切记String不是基本数据类型,是一个类,创建的是对象
// 两种创建方式
String s1 = "abc"; // 字面量定义方式,创建的字符串在常量池中,常量池中不会存相同的常量
s1 = "aaa"; //重新指定内存,s1指向新内存区域
String s2 = new String("hello");
// 执行替换操作,会返回新的字符串,显然原字符串没改变,即重新指定内存区存放新字符串
s3 = s2.replace('e', 'E');
当对字符串重新赋值时,重新指定内存区域,把原变量名指向新的内存区。
当进行链接操作时,也是重新指定内存区域,将原内存区域的值和新的值写到新的内存中。
执行替换操作,也是重新指定内存区域,存放新字符串。
**new String(“hello”)的方式创建字符串时,在堆中分配空间,存放的是常量池中字符串的地址,对象的引用指向的是堆内存的地址。
// 以字面量方式赋值
Person p1 = new Person("Tom",4);
Person p2 = new Person("Tom",4);
System.out.println(p1.name == p2.name); //true
System.out.println(p1.name.equals(p2.name)); //true
String str = new String("hello");
//面试题: 一共创建了两个对象:一个是在堆中,另一个是char[]对应的常量池中的数据
小结
- 常量与常量的拼接,结果在常量池中
- 只要有一个是变量参与拼接,结果就在堆中
- 拼接结果调用intern(),返回值就在常量池中
public static void main(String[] args) {
String s1 = "hello";
String s2 = "world";
String s3 = "helloworld";
String s4 = "hello"+"world";
String s5 = s1 +"world";
String s6 = "hello" +s2;
String s7 = s1 +s2;
final s8 = "hello";
s9 = s8 + "world";
System.out.println(s3 == s4);//true
System.out.println(s3 == s5);//false
System.out.println(s3 == s6);//false
System.out.println(s3 == s7);//false
System.out.println(s6 == s7);//false
String s8 = s7.intern();
System.out.println(s3 == s8);//true
System.out.println(s9 == s4);//true
}
数组是引用数据类型
类型转换
String str = "123";
//int num = (int)str; 错误写法,只有存在父子关系的才能转换
int num = Integer.parseInt(str);
String s = String.valueOf(num);
// char[]
char[] chars = str.toCharArray();
String s1 = new String(chars);
// buye[]
byte[] bytes = str.getBytes();
String s = new String(bytes);
二、stringbuffer与stringbuilder
stringbuffer:可变字符序列,线程安全,效率低
stringbuilder:可变字符序列,线程不安全,效率高
二者底层都是用char[] value()来存储的。
StringBuffer sb1 = new StringBuffer();//默认申请的容量是16,但字符串长度为0
StringBuffer sb1 = new StringBuffer("str");//默认容量是str的长度加16,字符串长度是3
关于扩容:默认情况下,容量扩充为原来的2倍+2,并将原数据复制到新数组中。
stringbuffer常用方法
append(xxx) | 添加 |
---|---|
delete(int start,int end) | 删除 |
setCharAt(int n,char ch) | 修改 |
replace(int start,int end,String str) | 替换 |
charAt(int n) | 查找 |
insert(int offset,xxx) | 插入 |
for()+charAt()+toString | 遍历 |
在开发中,建议使用带参数的StringBuffer(int capacity)/StringBuilder(int capacity)构造器,可指定容量。单线程或不涉及到共享数据的情况下,可使用String BUilder
三 日期和时间
long l = System.currentTimeMillis();
System.out.println(l);// 这个时间差被称为时间戳,1970年1月1日0时0分0秒至今
java.util.Date date1 = new Date(12422108915L);
java.util.Date date2 = new java.util.Date(3892436319L);
//date = (Date)date2; 报错,因为new 的是父类,不能转成子类
date = (Date)date1;
/* import java.util.Date与import java.sql.Date
* sql.Date是util.Date的子类,专用于数据库中的日期类
* 二者可进行相互转换
*
* */
求子串个数
public static int subStringCount(String mainStr,String sunStr){
int count = 0;
int index = 0;
if ((mainStr.length()-sunStr.length())>=0){
while ((index = mainStr.indexOf(sunStr))!=-1){
count++;
mainStr = mainStr.substring(index+sunStr.length());
}
// 方式二:高效
while ((index = mainStr.indexOf(sunStr,index))!=-1){
count++;
index += sunStr.length();
}
}
return count;
}
分析:方式一这里用mainStr.indexOf(subStr)可得到字串首次在主串中的位置,然后可以让主串从index+sunStr.length()的位置开始继续比较。方式二是直接在主串中通过改变下标寻找。
求最大字串
public static String getAMxString(String str1,String str2){
if (str1!=null && str2!=null){
String maxString = (str1.length()>=str2.length())?str1:str2;
String minString = (str1.length()<str2.length())?str1:str2;
int length = minString.length();
for (int i = 0; i < length; i++) {
for (int x=0,y=length-i;y<=length;x++,y++){
String substr = minString.substring(x,y);
if(maxString.contains(substr)){
return substr;
}
}
}
}
return null;
}
分析:以字串为主,从字串的全部开始于主串比较,发现相同的就返回。(只有一个最大字串的前提)
一个问题
String str = null;
StringBuffer ab = new StringBuffer();
ab.append(str);
System.out.println(ab); // "null"字符串
System.out.println(ab.length()); //4
StringBuffer sb = new StringBuffer(str); //NullPointerException
System.out.println(sb);
//源码如下
private AbstractStringBuilder appendNull() {
int c = count;
ensureCapacityInternal(c + 4);
final char[] value = this.value;
value[c++] = 'n';
value[c++] = 'u';
value[c++] = 'l';
value[c++] = 'l';
count = c;
return this;
}
// SimpleDateFormat
Date date = new Date();
System.out.println(date);//Tue Mar 23 16:42:49 CST 2021
//将日期类对象格式化为字符串
SimpleDateFormat sdf = new SimpleDateFormat();
String dateString = sdf.format(date);
System.out.println(dateString);//21-3-23 下午4:43 默认格式
// 将字符串解析为日期对象
Date date1 = sdf.parse(dateString);
System.out.println(date1); //Tue Mar 23 16:48:00 CST 2021
// 自定义日期格式
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String format = sdf1.format(date);
System.out.println(format); //2021-03-23 04:51:39
// 将util下的日期对象转为sql下的日期对象
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
Date date2 = sdf2.parse("2020-8-10");
java.sql.Date date3 = new java.sql.Date(date2.getTime());
System.out.println(date3); //2020-08-10
//calendar
// Calendar是一个抽象类,调用其静态方法创建对象
Calendar calendar = Calendar.getInstance();
// 常用方法
System.out.println(calendar.get(Calendar.DAY_OF_YEAR)); //82
calendar.set(Calendar.DAY_OF_YEAR,3);
System.out.println(calendar.get(Calendar.DAY_OF_YEAR)); //3
calendar.add(Calendar.DAY_OF_YEAR,3);
System.out.println(calendar.get(Calendar.DAY_OF_YEAR)); //6
// 类型转换
Date time = calendar.getTime();
System.out.println(time);
Date date = new Date();
calendar.setTime(date);
System.out.println(calendar.get(Calendar.DAY_OF_YEAR)); //82
日历类的一月是0,十二月是11,周日是1,周六是7
新的时间日期API
LocalDate localDate = LocalDate.now();
LocalTime localTime = LocalTime.now();
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDate); //2021-03-23
System.out.println(localTime); //20:58:50.090
System.out.println(localDateTime);//2021-03-23T20:58:50.090
// of 获取指定的时间
localDateTime = LocalDateTime.of(2028,10,8,12,2,4);
System.out.println(localDateTime); //2028-10-08T12:02:04指定多少就是多少,无偏移量
//获取相关属性
System.out.println(localDateTime.getDayOfMonth());
System.out.println(localDateTime.getDayOfWeek());
//配置相关属性
LocalDateTime localDateTime1 = localDateTime.withDayOfMonth(20);
System.out.println(localDateTime1);
System.out.println(localDateTime);//未被修改,即体现不可变性
LocalDateTime localDateTime2 = localDateTime.plusDays(4);//当前日期加4天
LocalDateTime localDateTime22 = localDateTime.minusDays(4);//当前日期减4天
// 瞬时
Instant instant = Instant.now();
System.out.println(instant);//2021-03-23T13:16:55.661Z
OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
System.out.println(offsetDateTime);//2021-03-23T21:16:55.661+08:00
DateTimeFormatter dtf = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
LocalDateTime now = LocalDateTime.now();
System.out.println(now);//2021-03-23T21:26:26.397
// 格式化
String format = dtf.format(now);
System.out.println(format);//2021-03-23T21:26:26.397
// 解析
TemporalAccessor parse = dtf.parse(format);
System.out.println(parse);//{},ISO resolved to 2021-03-23T21:27:29.697
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);//可更改格式
System.out.println(dateTimeFormatter.format(parse));//2021年3月23日 下午09时29分17秒
DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");//自定义格式
比较器
像String,包装类实现了comparable接口,重写了compareato(obj)方法,可比较两个对象大小。
自定义的类可实现comparable接口,重写比较的方法,即可实现自定义类的比较。
public class Products implements Comparable{
private int price;
private String name;
public Products(int price, String name) {
this.price = price;
this.name = name;
}
@Override
public String toString() {
return "Products{" +
"price=" + price +
", name='" + name + '\'' +
'}';
}
@Override
public int compareTo(Object o) {
if (o instanceof Products){
Products products = (Products)o;
if (this.price>products.price){
return 1;
}else if (this.price<products.price){
return -1;
}else {
return this.name.compareTo(products.name);//String类已重写comparable方法
}
}
throw new RuntimeException("类型错误》");
}
public static void main(String[] args) {
Products[] arr = new Products[5];
arr[0] = new Products(60,"savaMe");
arr[1] = new Products(2,"aavaEE");
arr[2] = new Products(12,"javaSE");
arr[3] = new Products(28,"spring");
arr[4] = new Products(21,"havaweb");
Arrays.parallelSort(arr);
System.out.println(Arrays.toString(arr));
}
}
comparator 定制排序方法
关键点是重写compare(Object o1,Object o2)方法
String[] arrs = {"aa","nv","1ee","de","we"};
Arrays.sort(arrs, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
String s1 = (String)o1;
String s2 = (String)o2;
return -s1.compareTo(s2);
}
});
System.out.println(Arrays.toString(arrs));
comparator 接口是在使用时指定排序方法,一次性或使用次数较小的时候可以用,comparable接口是类实现的,任何对象都可以使用。
system类
math类
bigInteger
bigdecimal
枚举类
类的对象是有限个、确定的,当需要定义一些常量时,建议使用枚举类,若枚举类只有一个对象,则可作为单例模式的实现方式。
public enum Seasons {
SPRING("春天"),
SUMMER("夏天"),
AUTUMN("秋天"),
WINTER("冬天");
private String name;
Seasons(String name) {
this.name = name;
}
public static void main(String[] args) {
System.out.println(Seasons.SUMMER);//SUMMER
}
}
几个方法
- values():返回枚举类的所有对象
- valueOf(String str):把一个字符串转换为枚举类对象,要求字符串必须是枚举类对象对应的名字,不含会抛异常
- toString():返回当前对象的名称。
如果枚举类实现了某个接口,可让每个对象分别重写方法,产生不同的行为。枚举类的对象的修饰符是public static final
java中,继承时子类空参构造器默认调用父类的空参构造器,如果子类没有空参构造,则父类也无需写空参构造;子类的的有参构造器必默认也是调用父类的有参构造。