Java (day14) serialization and deserialization, generics, collections

Posted by simona_85 on Fri, 17 Dec 2021 13:13:56 +0100

Serialization: it is the process of permanently saving the java objects in the program in the disk, which is equivalent to writing out

Direction: out. The stream used is ObjectOutputStream

Serializable interfaces are implemented to serialize objects for output: public implement Serializable

Serializable is an empty interface and has no method

Deserialization: the process of reading and restoring only the data stored in the serialized file to the java program

Direction: in. The stream used is: ObjectInputStream

Override tostring to convert address values to attributes

package cn.tedu.seri;

import java.io.Serializable;

//Material class used for test serialization
public class Student implements Serializable {
    private String name;
    private int age;
    private String addr;
    private  char gender;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }

    public char getGender() {
        return gender;
    }

    public void setGender(char gender) {
        this.gender = gender;
    }
    public Student() {
        System.out.println("I am Student Nonparametric structure of");
    }

    public Student(String name, int age, String addr, char gender) {
        super();   //Call the constructor of the parent object
        this.name = name;
        this.age = age;
        this.addr = addr;
        this.gender = gender;
        System.out.println("I am Student All parameter structure of");
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", addr='" + addr + '\'' +
                ", gender=" + gender +
                '}';
    }
}
package cn.tedu.seri;

import java.io.*;

//Test serialization and deserialization
public class TestSerializable {
    public static void main(String[] args) {
        method1();//serialize
        method2();//Deserialization
    }

    private static void method1() {
        ObjectOutputStream out=null;
        try {
            out=new ObjectOutputStream(new FileOutputStream("D:\\read\\1.txt"));
            Student obj=new Student("Spongebob",3,"The sea",'male');
            out.writeObject(obj);
            System.out.println("Congratulations on your successful serialization");
        } catch (Exception e) {
            System.out.println("Serialization failed");
            e.printStackTrace();
        }finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void method2() {
        ObjectInputStream in=null;
        try {
            in=new ObjectInputStream(new FileInputStream("D:\\read\\1.txt"));
            System.out.println(in.readObject());
            System.out.println("Congratulations on the successful deserialization");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Deserialization failed");
        }finally {
            try {
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
Operation results:
I am Student All parameter structure of
 Congratulations on your successful serialization
Student{name='Spongebob', age=3, addr='The sea', gender=male}
Congratulations on the successful deserialization

Generic:

Meaning: for the part decorated with < >, the type in < type > must be a reference type, not a basic type, and the generic type will be deleted after compilation

Objective: to constrain element types in a collection through generics

Advantages: you can report errors in advance and report errors at compile time, rather than after running

Efficient for loop: foreach loop

Disadvantages: there is no way to operate the value according to the subscript. It can only be convenient from beginning to end

Advantages: it is simpler and more efficient than the ordinary for loop writing method

Syntax: for (2 3:1) {loop body}: 1 is the content to be traversed, and 2 3 is the type and name of the specific element traversed in each round

package cn.tedu.collection;

import java.util.Arrays;

//Advantages for testing generics
public class TestGeneric2 {
    public static void main(String[] args) {

        Integer[] a={1,2,3,4,5,6,7,8,9,10};
        print(a);
        String[] b={"eldest brother","second elder brother","Third brother","Fourth brother","Five brothers","Six brothers","Little brother"};
        print(b);
        Double[] c={6.0,6.6,6.66,6.666,6.6666};
        print(c);
    }

    private static void print(String[] a){
        for(String mmm:a){
            System.out.println(mmm);
        }
    }
    private static void print(Double[] c){
        for (Double m:c){
            System.out.println(m);
        }
    }
    private static void print(Integer[] a) {
        //Normal for loop
        for (int i = 0; i <a.length ; i++) {
            System.out.println(a[i]);
        }
        //Efficient for loop: foreach loop
        for(Integer k:a){
            System.out.println(k);
        }
    }


}
Operation results:
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10
 eldest brother
 second elder brother
 Third brother
 Fourth brother
 Five brothers
 Six brothers
 Little brother
6.0
6.6
6.66
6.666
6.6666

Process finished with exit code 0

Generics can realize the writing of general code, and E is used to indicate that the type of element is element type

Syntax requirements for generics:

If a generic type is used on a method, it must appear in two places at the same time, one is the type of the incoming parameter, and the other is the generic type before the return value type

package cn.tedu.collection;

import java.util.Arrays;

//Advantages for testing generics
public class TestGeneric2 {
    public static void main(String[] args) {

        Integer[] a={1,2,3,4,5,6,7,8,9,10};
        print(a);
        String[] b={"eldest brother","second elder brother","Third brother","Fourth brother","Five brothers","Six brothers","Little brother"};
        print(b);
        Double[] c={6.0,6.6,6.66,6.666,6.6666};
        print(c);
    }

    private static<E> void print(E[] e) {
        for(E ddd:e){
            System.out.println(ddd);
        }
    }
Operation results:
1
2
3
4
5
6
7
8
9
10
 eldest brother
 second elder brother
 Third brother
 Fourth brother
 Five brothers
 Six brothers
 Little brother
6.0
6.6
6.66
6.666
6.6666

Collection collection

Create an object and add elements to the collection

package cn.tedu.collection2;

import java.util.ArrayList;
import java.util.Collection;

//This class is used to test the collection interface
public class TestCollection {
    public static void main(String[] args) {
        //Create collection related collection objects
        Collection<Integer> c=new ArrayList<>();
        //Common methods in test sets
        c.add(100);
        c.add(200);
        c.add(300);
        c.add(400);
        c.add(500);
        System.out.println(c);
       
    }
}
Operation results:
[100, 200, 300, 400, 500]

Empty collection

 c.clear();
 System.out.println(c);
Operation results:
[]

Interpret whether the collection contains the element

System.out.println(c.contains(200));
Operation results:
true

Determine whether the collection is empty

System.out.println(c.isEmpty());
Operation results:
false

Judge the length of the set

System.out.println(c.size());
Operation results:
4

Replace the specified set with an array

System.out.println(Arrays.toString(c.toArray()));
Operation results:
[200, 300, 400, 500]

collection operations between collections

Merge set

c.addAll(c2);
Operation results:
[200, 300, 400, 500, 2, 4, 5]

Determines whether a collection contains all the elements of another collection

c.contains(c2)
Operation results:
true

Keep the common elements in the c set that belong to the c2 set

c.retainAll(c2);
Operation results:
[2, 4, 5]

Delete all elements belonging to c2 set in c set

c.removeAll(c2);
Operation results:
[]
Iteration and traversal of sets
 1. Get the iterator corresponding to the set
 2. Determine whether the next element in the set can be iterated through the iterator
 3. Elements currently iterated through the iterator
package cn.tedu.collection2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

//This class is used to test the collection interface
public class TestCollection {
    public static void main(String[] args) {
        
        //Operations between multiple sets
        Collection<Integer> c2=new ArrayList<>();
        c2.add(2);
        c2.add(4);
        c2.add(5);
        System.out.println(c2);
        
        Iterator<Integer> it = c2.iterator();
        while (it.hasNext()){
            System.out.println(it.next());
        }

    }
}

Operation results:
2
4
5

List collection

Collection: it is orderly, can put duplicate data, and inherits the collection method

package cn.tedu.collection2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//Test list interface
public class TestList {
    public static void main(String[] args) {
        //Test methods that inherit collect
        List<String> list=new ArrayList<>();
        list.add("Big baby");
        list.add("Er wa");
        list.add("Three children");
        list.add("Four children");
        list.add("Five children");
        list.add("Six children");
        list.add("Seven children");
        System.out.println(list);
        System.out.println(list.contains("Er wa"));
        System.out.println(list.equals("Er wa"));
        System.out.println(list.isEmpty());
        System.out.println(list.remove("Three children"));
        System.out.println(list.size());
        System.out.println(Arrays.toString(list.toArray()));
    }
}
Operation results:

Add element at specified location

list.add("Little butterfly");
list.add(2,"Little butterfly");
list.add(1,"Snake essence");
System.out.println(list);
Operation results:
[Big baby, Er wa, Three children, Four children, Five children, Six children, Seven children]
[Big baby, Er wa, Little butterfly, Three children, Four children, Five children, Six children, Seven children, Little butterfly]
[Big baby, Snake essence, Er wa, Little butterfly, Three children, Four children, Five children, Six children, Seven children, Little butterfly]

Gets the first and last indexes

System.out.println(list.indexOf("Little butterfly"));
System.out.println(list.lastIndexOf("Little butterfly"));
System.out.println(list);
Operation results:
3
9

Delete element based on index

list.remove(5);
System.out.println(list);
Operation results:
[Big baby, Snake essence, Er wa, Little butterfly, Three children, Five children, Six children, Seven children, Little butterfly]

Get element by subscript

System.out.println(list.get(3));
Operation results:
Little butterfly

Adds an element at the specified location

System.out.println(list.set(5,"Little tiger"));
System.out.println(list);
Operation results:
[Big baby, Snake essence, Er wa, Little butterfly, Three children, Little tiger, Six children, Seven children, Little butterfly]

List sets and operations between sets

package cn.tedu.collection2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//Test list interface
public class TestList {
    public static void main(String[] args) {
        //Test methods that inherit collect
        List<String> list=new ArrayList<>();
        list.add("Big baby");
        list.add("Er wa");
        list.add("Three children");
        list.add("Four children");
        list.add("Five children");
        list.add("Six children");
        list.add("Seven children");
        System.out.println(list);

        List<String> list2=new ArrayList<>();
        list2.add("1");
        list2.add("2");
        list2.add("3");
        list2.add("4");
        System.out.println(list2);

        list.addAll(1,list2);//Add at specified location
        System.out.println(list);


    }
}
Operation results:

[Big baby, 1, 2, 3, 4, Er wa, Three children, Four children, Five children, Six children, Seven children]

Topics: Java Back-end