java基础题

文章目录
  1. 1. 自增变量
  2. 2. 初始化和实例初始化
  3. 3. 方法的参数传递机制
  4. 4. List 分批代码

自增变量

@Test
public void test01() {
int i = 1;
i = i++;
int j = i++;
int k = i + ++i * i++;
System.out.println("i=" + i);
System.out.println("j=" + j);
System.out.println("k=" + k);
}

输出结果:

i=4
j=1
k=11

i++:先使用再 +1

++i:先 +1 再使用

初始化和实例初始化

public class Father {

private int i = test();
private static int j = method();

static {
System.out.println("Father 静态代码块");
}

public Father() {
System.out.println("Father 构造方法");
}

{
System.out.println("Father 实例代码块");
}

public int test() {
System.out.println("Father 普通方法");
return 1;
}

public static int method() {
System.out.println("Father 静态方法");
return 1;
}
}
public class Son extends Father{

private int i = test();
private static int j = method();

static {
System.out.println("Son 静态代码块");
}

public Son() {
System.out.println("Son 构造方法");
}

{
System.out.println("Son 实例代码块");
}

@Override
public int test() {
System.out.println("Son 普通方法");
return 1;
}

public static int method() {
System.out.println("Son 静态方法");
return 1;
}

public static void main(String[] args) {
Son s1 = new Son();
System.out.println("-----");
Son s2 = new Son();
}
}

输出结果:

Father 静态方法
Father 静态代码块
Son 静态方法
Son 静态代码块
Son 普通方法
Father 实例代码块
Father 构造方法
Son 普通方法
Son 实例代码块
Son 构造方法
-----
Son 普通方法
Father 实例代码块
Father 构造方法
Son 普通方法
Son 实例代码块
Son 构造方法

方法的参数传递机制

public class Exam4 {

public static void main(String[] args) {
int i = 1;
String str = "hello";
Integer num = 200;
int[] arr = {1, 2, 3, 4, 5};
MyData my = new MyData();

change(i, str, num, arr, my);

System.out.println("i= " + i);
System.out.println("str= " + str);
System.out.println("num= " + num);
System.out.println("arr= " + Arrays.toString(arr));
System.out.println("my.a= " + my.a);
}

public static void change(int j, String s, Integer n, int[] a, MyData m) {
j += 1;
s += "world";
n += 1;
a[0] += 1;
m.a += 1;
}
}

class MyData {
int a = 10;
}

输出结果:

i=  1
str= hello
num= 200
arr= [2, 2, 3, 4, 5]
my.a= 11

List 分批代码

当 List 集合数据量比较大时,需要对集合分组,分批处理数据

public static void main(String[] args) {
// 集合
List<String> list = new ArrayList<>();
for (int i = 0; i < 100; i++) {
list.add(i + "");
}
// 分组长度
int groupSize = 10;
int size = list.size();
int count = size % groupSize == 0 ? size / groupSize : size / groupSize + 1;
for (int i = 0; i < count; i++) {
int fromIndex = i * groupSize;
int toIndex = (i + 1) * groupSize > size ? size : (i + 1) * groupSize;
List<String> subList = list.subList(fromIndex, toIndex);
System.out.println(subList);
}
}