Java 常用 API
string
- 创建字符串对象
public class HelloWorld {public static void main(String[] args) {// 1. 直接使用双引号得到字符串对象,封装字符串数据 (推荐使用)String name = "tomato";System.out.println(name); // tomato// 2. new String创建字符串对象,并调用构造器初始化String gender = new String();System.out.println(gender); // ""String hobby = new String("coding");System.out.println(hobby); // coding// 3. 数组char[] arr = {'G', 'o', 'o', 'd'};String res = new String(arr);System.out.println(res); // Good// 3. 数组byte[] arr2 = {97, 98, 99};String res2 = new String(arr2); // ASCII码System.out.println(res2); // abc}
}
- 字符串常用方法
public class HelloWorld {public static void main(String[] args) {String s1 = "Tomato";String s2 = "Potato";// 1.输出字符串长度System.out.println(s1.length()); // 6// 2.通过索引取字符System.out.println(s1.charAt(0)); // T// 3.字符串变成字符数组char[] arr = s1.toCharArray();for (int i = 0; i < arr.length; i++) {System.out.println(arr[i]);}// 4.判断字符串内容是否一致System.out.println(s1.equals(s2)); // equals是比较字符串内容是否一样// 注意不要使用 s1 == s2 进行判断,它是比较内存地址是否一样// 5.忽略大小写比较字符串内容System.out.println(s1.equalsIgnoreCase(s2));// 6.截取字符串内容 (包前不包后)String s3 = s1.substring(0, 4);System.out.println(s3); // Toma// 7. 从当前索引位置一直截取到字符串末尾String s4 = s1.substring(2); // 从索引2开始一直截取System.out.println(s4); // mato// 8.替换字符串中的某些内容String info = "卧槽,厉害!";System.out.println(info.replace("卧槽", "**"));// 9.是否包含某关键字 (严格区分大小写)System.out.println(info.contains("卧槽")); // true// 10.是否以某字符串开头System.out.println(s1.startsWith("To")); // true// 11.分割字符串String s5 = "李大明,李二明,李三明,李小明";String[] arr2 = s5.split(","); // 返回值为数组,数组里面存放一个个被分割的字符串for (int i = 0; i < arr2.length; i++) {System.out.println(arr2[i]);}}
}
-
字符串注意事项
-
String 的对象是不可变字符串对象:我们每次试图改变字符串对象,实际上是产生了新的字符串对象,变量每次都是指向新的字符串对象,之前对象的内容确实没有改变。
-
只要是以 “…” 方式写出的字符串对象,会存储到字符串常量池,且相同内容的字符串只存储一份。
-
但是通过 new 方式创建字符串对象,每 new 一次都会产生一个新的对象放在堆内存中。
-
-
集合
-
概念:集合是一种容器,用来装数据的,类似于数组。
-
特点:与数组大小难以变化不同,集合的大小是可变的,所以开发中用的也多。
-
种类:集合的种类很多,本篇只对 ArrayList 进行基本介绍。
-
ArrayList 介绍:
- 它是集合中最常用的一种,ArrayList 是泛型类,可以约束存储的数据类型。
- 操作展示
-
import java.util.ArrayList;public class HelloWorld {public static void main(String[] args) {// 1.1 创建一个ArrayList的集合对象ArrayList list = new ArrayList();// 1.2 向集合里面添加任意内容list.add(666);list.add("金刚");list.add(3.14);System.out.println(list);// 2.1 创建一个String类型的集合对象// ArrayList<String> list2 = new ArrayList<String>();ArrayList<String> list2 = new ArrayList<>(); // 因为前面写了String,后面的<>里面可以不写String// 2.2 向集合里面添加String类型的内容list2.add("神奇");list2.add("宝贝");System.out.println(list2);// 3 往集合中的某个索引位置处添加一个数据list2.add(0, "MySQL");System.out.println(list2);// 4 根据索引获取元素System.out.println(list2.get(0)); // MySQL// 5 获取集合的大小 (即存储元素的个数)System.out.println(list2.size()); // 3// 6 根据索引删除集合中的某个元素值,会返回被删除的元素值给我们System.out.println(list2.remove(0)); // MySQL// 7 直接删除某个元素值(默认删除第一次出现的元素值),删除成功后返回true,反之falseSystem.out.println(list2.remove("神奇"));// 8 修改某个索引位置处的数据,修改后会返回原来的值给我们System.out.println(list2.set(0, "哈哈哈"));}
}