JAVA review process control, array, generic, collection

1. For a detailed tutorial, see: Program Structure (Process Control Statement)

Insert picture description here

2. Matters needing attention:

1. The case cannot use floating point types.
2. If you encounter loop nesting, the break statement will only make the program flow out of the innermost loop structure that contains it, that is, out of a loop
3. Break and continue provide " Label" function
Insert picture description here

Three, array

Insert picture description here
Example problem analysis:
a 3 x 3 network, put the numbers from 1 to 9 into the grid, so that the value of each row, column and each diagonal can be the same.

public class NineGrids {
    
    // 创建NineGrids类
	public static void main(String[] args) {
    
    
		// 声明int类型的数组并分配内存(三阶方阵)
		int arr[][] = new int[3][3];
		// 确定数字“1”的位置
		int a = 2;// 第3行的下标
		int b = 3 / 2;// 第2列的下标
		for (int i = 1; i <= 9; i++) {
    
    // 给数组赋值
			arr[a++][b++] = i;// 避免数组下标越界
			if (i % 3 == 0) {
    
    // 如果i是3的倍数
				a = a - 2;
				b = b - 1;
			} else {
    
    // 如果i不是3的倍数
				a = a % 3;
				b = b % 3;
			}
		}
		System.out.println("九宫格:");
		// 遍历数组
		for (int i = 0; i < 3; i++) {
    
    
			for (int j = 0; j < arr.length; j++) {
    
    
				System.out.print(arr[i][j] + " ");// 输出数组中的数据
			}
			System.out.println();// 换行
		}
	}
}

Four, generic

(1) What is generic? (Enable the program to define safe data types)

The parameterized type in java is called generic type, the following figure is an example
Insert picture description here

(2) Define generic classes

**Syntax: **Class name<type parameter 1, type parameter 2,...type parameter n>{}

public class Demo<T>{
    
    
	T username;
	T method(T t){
    
    }
}

(Three) the usage of generics

In the development process, if you need to specify parameter types dynamically, then you need to use generics.

1. Declare multiple types when defining a generic class

class method<T1,T2>

2. Declare the array type when defining a generic class

When defining a generic type, you can also declare an array type

2. The collection class declares the type of element

The application of generics in the collection can ensure the uniqueness of the element types in the collection. Thereby improving the security and maintainability of the code.

(4) How to use generics

public class Demo030<T> {
    
    
    T bankName; //银行名称
    T time; //存款时间
    T username; //户名
    T cardNum; //卡号
    T currency; //币种
    T inAccount; //存款金额
    T leftAccount; //账户余额
    public static void main(String[] args) {
    
    
        Demo030<Object> list = new Demo030<Object>(); //创建一个String类型的BankList对象
        list.bankName = "中国建设银行"; //初始化“银行名称”
        list.time = new Date(); //初始化“存款时间”
        list.username = "赵四"; //初始化“户名”
        list.cardNum = "6666 7777 8888 9996 789"; //初始化“卡号”
        list.currency = "RMB"; //初始化“币种”
        list.inAccount = 8888.00; //初始化“存款金额”
        list.leftAccount = 18888.89; //初始化“账户余额”
        DecimalFormat df = new DecimalFormat("###,###.##"); //创建DecimalFormat对象,用来格式化Double类型的对象
        System.out.println(
                "银行名称:" + list.bankName
                        + "\n存款时间:" + list.time
                        + "\n户  名:" + list.username
                        + "\n卡  号:" + list.cardNum
                        + "\n币  种:" + list.currency
                        + "\n存款金额:" + df.format(list.inAccount)
                        + "\n账户余额:" + df.format(list.leftAccount)
        ); //输出上述信息
    }
}

Five, the overview of the collection

(1) Are arrays really useful? What is the difference between array and collection?

It's not easy to use, because the length of the array is fixed, and the length of the collection is variable (like a train, which can be dynamically added to the carriage). The array can store basic data types and objects. The collection can only store objects. Including (LIst, set and Map collection)
Insert picture description here

(2) Common methods and descriptions of Collection interface

Insert picture description here

(Three) List collection

The List collection includes the List interface and all the implementation classes of the List interface
. The elements in the List collection are allowed to be repeated, and the order of the elements is the order in which the elements are added. The
user can access the elements in the collection through the index
1, the List interface
Insert picture description here
2, and the implementation of the List interface Class
①ArrayList saves the elements in the collection in the form of an array, and can access the elements in the collection randomly and quickly according to the index position.
②LinkedList saves the elements in the collection in a linked list structure. The performance of random access to the elements in the collection is poor, but the performance of inserting elements into the collection and deleting elements in the collection is excellent.
List list = new ArrayList<>();
List list2 = new LinkedList<>();
Insert picture description here
3. Iterator iterator (advantages: traverse all the elements in the collection and execute efficiently)
Insert picture description here
Insert picture description here
4. Case analysis

import java.util.*;

public class Demo01 {
    
    
    public static void main(String[] args) {
    
    
        //实例化集合类对象
        List<String> list = new ArrayList<>();
        //向集合中添加元素
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("12314213");
        //创建迭代器
        Iterator<String> it = list.iterator();
        //判断是否有下一个元素
        while (it.hasNext()){
    
    
            //获取集合中的元素
            String str = it.next();
            //打印
            System.out.println(str);
        }
    }
}
(4) Set collection

The elements in the Set collection are not sorted in a specific way, they are simply placed in the collection, and the elements in the Set collection cannot be repeated.
Insert picture description here
1. TreeSet (tree set, stored in order)
Insert picture description here
2. Added methods of TreeSet class
Insert picture description here
Both the HashSet class and the TreeSet class are implementation classes of the Set interface, and neither of them allow duplicate elements. But the HashSet class does not care about the order of the elements when traversing the elements in the collection, while the TreeSet class traverses the elements in the collection in natural order (ascending order)
3. Case analysis

public class Person implements Comparable {
    
    
    int id;
    int age;
    String name;

    @Override
    public int compareTo(Object o) {
    
    
        Person p;
        //判断是否为person类
        if(o instanceof Person){
    
    
            //强制转换
            p = (Person)o;
        }else{
    
    
            //表示传入的参数比我本身要小
            return -1;
        }
        int diff = this.age - p.age;
        if(diff != 0){
    
    
            //差值除以本身绝对值,可以得到+1 或者-1的值
            diff = diff / Math.abs(diff);
        }
        return diff;
    }
    public Person(int id, int age, String name) {
    
    
        this.id = id;
        this.age = age;
        this.name = name;
    }
    @Override
    public String toString() {
    
    
        return "Person{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}
public class Demo {
    
    
    public static void main(String[] args) {
    
    
        Set set = new TreeSet();
        Person p1 = new Person(1,18,"熊猫");
        Person p2 = new Person(2,33,"小明");
        Person p3 = new Person(3,22,"梦缘");
        //添加到集合
        set.add(p1);
        set.add(p2);
        set.add(p3);
        set.add(p3);//重复的元素不会被添加到集合中
        System.out.println(set.size());

        //创建迭代器
        Iterator it = set.iterator();
        while (it.hasNext()){
    
    
            System.out.println(it.next());
        }
    }
}

Insert picture description here

(5) Map collection

Insert picture description here
method:keySet() returns the set collection formed by all the key objects in the collection
values() returns the Collection collection formed by all the value objects in the collection

Insert picture description here
1. Case analysis one

import java.util.*;
public class HashMapTest {
    
    
	public static void main(String[] args) {
    
    
		Map<String, String> map = new HashMap<>(); // 创建Map集合对象
		map.put("ISBN 978-7-5677-8742-1", "Android项目开发实战入门"); // 向Map集合中添加元素
		map.put("ISBN 978-7-5677-8741-4", "C语言项目开发实战入门");
		map.put("ISBN 978-7-5677-9097-1", "PHP项目开发实战入门");
		map.put("ISBN 978-7-5677-8740-7", "Java项目开发实战入门");
		Set<String> set = map.keySet(); // 构建Map集合中所有key的Set集合
		Iterator<String> it = set.iterator(); // 创建Iterator迭代器
		System.out.println("key值:");
		while (it.hasNext()) {
    
     // 遍历并输出Map集合中的key值
			System.out.print(it.next() + " ");
		}
		Collection<String> coll = map.values(); // 构建Map集合中所有value值的集合
		it = coll.iterator();
		System.out.println("\nvalue值:");
		while (it.hasNext()) {
    
     // 遍历并输出Map集合中的value值
			System.out.print(it.next() + " ");
		}
	}
}

Learn more:It is recommended to use the HashMap class to implement the Map collection, because the Map collection implemented by the HashMap class is more efficient to add and delete mapping relationships; and if the elements in the Map collection are in a certain order, the TreeMap class should be used to implement the Map collection.

(6) Summary

1. The List collection is concerned with indexes, and the elements in the List collection are stored in order;
2. The Set collection is concerned with uniqueness, and its values ​​are not allowed to be repeated;
3. The Map collection is concerned with unique identifiers (key) , It maps a unique key to an element;
Insert picture description here

Guess you like

Origin blog.csdn.net/javaScript1997/article/details/108569664