slacr_

Just to record my life and thoughts.
笔记/编程/杂乱/极简

[Java笔记]数组&字符串

Apr 24, 2023Java2176 words in 15 min

Java笔记

数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Main {
public static void main(String[] args) {
// 声明数组
int[] arr_1;
String arr_2[]; // 两种形式
// 创建数组
arr_1 = new int[5];
arr_2 = new String[5];
// Java数组大小可以在运行时指定, C/C++不允许, 因为声明的时候仅要求确定引用(数组名);

// 数组初始化器
double[] arr_3 = new double[]{1.0, 2.1, 3.2, 4.3};
double[] arr_s = {1.0, 4.0}; // 简写
// 声明数组的同时也可以对数组元素初始化, 也称静态初始化

// 增强的for循环, 标识符获取每次循环的值
for (double v : arr_3) {
System.out.print(v + " ");
}
System.out.println();

// 数组复制, 调用System.arraycopy()方法
double[] arr_4 = new double[6];
System.arraycopy(arr_3,0,arr_4, 0, 3);
for (double v : arr_4) {
System.out.print(v + " ");
}
System.out.println();
}
}

可变参数(variable argument)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Main {
// 函数参数表的最后一个参数为 ... arr, 有点像 js 里面的 数组 解构符
public static double getAVG(String sign, double ... params) {
System.out.println(sign);
double avg = 0;
for (int i = 0; i < params.length; i++) {
avg += params[i];
}
return avg / params.length;
}
public static void main(String[] args) {
System.out.println(getAVG("slacr_", 3.0, 4.0, 5.0));
System.out.println(getAVG("re", 2.0, 8.0));
}
}

Arrays 类

Arrays 的 sort()方法可以对数组元素排序。使用该方法的排序是稳定的 (stable), 即相等的元素在排序结果中不会改变顺序。对于基本数据类型,按数据的升序排序。对于对象数组的排序要求数组元素的类必须实现 Comparable 接口,若要改变排序顺序,还可以指定一个比较器对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Arrays.sort()
public class Main {
public static void main(String[] args) {
String[] arr_s = new String[]{"Bob", "Alice", "Haskell", "Ruby", "Scala"};
for (String arr : arr_s) {
System.out.print(arr + " ");
}
System.out.println();

Arrays.sort(arr_s);

for (String arr : arr_s) {
System.out.print(arr + " ");
}
System.out.println();


}
}
1
2
3
4
5
6
7
8
9
10
11
// Arrays.binarySearch()
public class Main {
public static void main(String[] args) {
int[] arr = {1, 3, 2, 4, 5};
Arrays.sort(arr); // 先排序
int res = Arrays.binarySearch(arr, 4);
System.out.println(res); // 找到返回下标
res = Arrays.binarySearch(arr, 100);
System.out.println(res); // 找不到返回 - 应该插入的位置 - 1, -6
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
int[] arr_c = Arrays.copyOf(arr, 6);
for (int i = 0; i < arr_c.length; i++) {
System.out.print(arr_c[i] + " ");
}
System.out.println(); // 1 2 3 0 0 0

int[] arr_cor = Arrays.copyOfRange(arr_c, 1, 5);
for (int i = 0; i < arr_cor.length; i++) {
System.out.print(arr_cor[i] + " ");
}
System.out.println(); // 2 3 0 0
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Main {
// fill() equals()
public static void main(String[] args) {
int[] arr = new int[5];
Arrays.fill(arr, 2, 5, 1);
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println(); // 0 0 1 1 1

int[] arr_2 = new int[5];
for (int i = 0; i < arr_2.length; i++) {
Arrays.fill(arr_2, i, i+1, arr[i]);
}

if(Arrays.equals(arr, arr_2)) System.out.println("equal"); // equal
}
}

多维数组

在Java中,二维数组是数组的数组
在创建二维数组时,也可以先为第一维分配空间,然后再为第二维分配空间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Main {
public static void main(String[] args) {
int[][] arr = new int[2][3];

int[][] arr_1 = new int[2][];
arr_1[0]= new int[10];
arr_1[1] = new int[5];
for (int i = 0; i < arr_1.length; i++) {
for (int j = 0; j < arr_1[i].length; j++) {
System.out.print(arr_1[i][j] + " ");
}
System.out.println();
}
}
}

矩阵乘法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
public class Matrix {
public int[][] m;
public Matrix(int m[][]) {
this.m = m;
}
public Matrix multiply(Matrix M){
int res[][] = new int[m.length][M.m[0].length];
for (int i = 0; i < res.length; i++) {
for (int j = 0; j < res[0].length; j++) {
for (int k = 0; k < m[0].length; k++) {
res[i][j] = res[i][j] + m[i][k] * M.m[k][j];
}
}
}
return new Matrix(res);
}

public void show(){
for (int i = 0; i < m.length; i++) {
if( i == 0 ) {
for (int j = 0; j < m[0].length; j++) {
if(j == 0) System.out.printf("┏ ");
else if(j == m[0].length - 1) System.out.printf(" ┓");
else System.out.printf(" ");
}
System.out.println();
}
for (int j = 0; j < m[i].length; j++) {
if( j == 0) System.out.printf("┃%-5d", m[i][j]);
else if( j == m[i].length - 1) System.out.printf("%-5d┃", m[i][j]);
else System.out.printf("%-5d", m[i][j]);
}
System.out.println();
if( i == m.length - 1 ) {
for (int j = 0; j < m[0].length; j++) {
if(j == 0) System.out.printf("┗ ");
else if(j == m[0].length - 1) System.out.printf(" ┛");
else System.out.printf(" ");
}
System.out.println();
}
}
}
}

// ========================================================

public class Main {
public static void main(String[] args) {
int[][] m_1 = {{1, 2, 1},
{-2, 4, 1}};
int[][] m_2 = {{4, 3, 0, -1},
{2, 3, 5, 2},
{1, 0, 6, 3}};
Matrix M_1 = new Matrix(m_1);
M_1.show();
Matrix M_2 = new Matrix(m_2);
M_2.show();
Matrix M_3 = M_1.multiply(M_2);
M_3.show();
}
}

字符串

1
2
3
4
5
6
7
8
9
10
public class Main {
public static void main(String[] args) throws UnsupportedEncodingException {
// 字面量 创建字符串
String str = "PHP is the best language all of the world!";
String str_1 = new String("A cup of Java");
byte[] b = str.getBytes("UTF-8");
String str_2 = new String(b, "UTF-8");
System.out.println(str_2);
}
}

一些方法:
public String(StringBuffer buffer)
public String(StringBuilder buffer)
public String substring(int beginIndex, int endIndex)
public String toUpperCase()
public String toLowerCase()
public String trim()
public boolean isEmpty()
public String concat(String str)
public String replace(char oldChar, char newChar)
public char charAt(int index)
public static String valueOf(double d) 将参数转字符串

查找
public int indexOf(int ch)
public int indexOf(int ch, int fromIndex)
public int indexOf(String str)
public int indexOf(String str, int fromIndex)
public int lastIndexOf(int ch)
public int lastIndexOf(int ch, int endIndex)
public int lastIndexOf(String str)
public int lastIndexOf(String str, int endIndex)

字符串转数组
public char[] toCharArray()
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
public byte[] getBytes()
public byte[] getBytes(String charsetName)

字符串比较
public boolean equals(String anotherString)
public boolean equalsIgnoreCase(String anotherString)
public int compareTo(String another) 比较Unicode值
public int compareToIgnoreCase(String anotherString)
public boolean startsWith(String prefix)
public boolean endsWith(String suffix)
public boolean contains(String str)
字符串拆分与组合
public String[] split(String regex)
public boolean matches(String regex)
public static String join(CharSequence delimiter, CharSequence ...elements)

命令行参数

public static void main(String []args){}
public static void main(String ...args){}
用CMD运行的时候指定, 或者在IDEA中可以,

Apply应用后在运行就可以了.

格式输出

public PrintStream printf(String format, Object ...args)

“%s"格式符也可以用在任何类型的数据上。对于”%s"格式符号,如果参数值为 null,结果输出 null; 如果参数实现了 Formatter 接口,结果是调用 args.formatTo()的结果,否则结果是调用 args.toString()的结果

public static String format(String format, Object ...args)
public static String format(Locale l, String format, Object ...args)
这两个方法的功能是按照参数指定的格式,将args格式化成字符串返回。此外,在java.io.PrintStream类、java.io.PrintWriter类以及 java.util.Formatter类中都提供了相应的format()方法。它们的不同之处是方法的返回值不同。在各自类中的 format()方法返回各自类的一个对象.

StringBuilder 和 StringBuffer

StringBuilder类和 StringBuffer类都表示可变字符串,即这两个类的对象内容是可以修改的。一般来说,只要使用字符串的地方,都可以使用 StringBuilder/StringBuffer类,它们比 String类更灵活。

StringBuilder

public StringBuilder()
创建一个没有字符的字符串缓冲区,初始容量为16个字符。此时length()方法的值为0,而capacity()方法的值为16
public StringBuilder(int capacity)
public StringBuilder(String str)
利用一个已存在的字符串对象 str创建一个字符串缓冲区对象,另外再分配16个字符的缓冲区

StringBuilder类除定义了 length()、charAt()、indexOf()、getChars()等方法外,还提供
了下列常用方法
public int capacity()
public void setCharAt(int index,char ch)
public StringBuilder append(String str)
public StringBuilder insert(int offset, String str)
public StringBuilder deleteCharAt(int index)
public StringBuilder delete(int start, int end)
public StringBuilder replace(int start, int end, String str)
public StringBuilder reverse()
public String substring(int start)
public String substring(int start, int end)
public void setLength(int newLength)
更多见文档 https://docs.oracle.com/en/java/javase/19/docs/api/java.base/java/lang/StringBuilder.html

知识点

  1. Java中String对象是不可变的字符串, 方法不能改变对象本身, 只返回新的字符串.
  2. 在 Java语言中不支持运算符重载,但有一个特例,即"+“运算符(包括+=)是唯一重载的运算符。该运算符除用于计算两个数之和外,还用于连接两个字符串。当用”+"运算符连接的两个操作数其中有一个是 String类型时,该运算即为字符串连接运算.
  3. StringBuffer类的实例是线程安全的,而StringBuilder类的实例不是线程安全的。如果不需要线程同步,建议使用 StringBuilder类

参考

  1. 《Java程序设计(第3版)》 IBSN 9787302485520
  2. Java API 文档
  • Author:

    slacr_

  • Copyright:

  • Published:

    April 24, 2023

  • Updated:

    April 24, 2023

Buy me a cup of coffee ☕.

1000000