The difference between Parcelable and Serializable in the detailed explanation of Android interview questions?

The difference between sequence Parcelable, Serializable? (Ali)

Explain in detail

Essential Skills for Architects to Build a Foundation "NDK Topic-JNI Practical Chapter"

What is this question trying to investigate?

Master the principle of serialization interface implementation, and use it reasonably in work for different scenarios

Knowledge points of inspection

Principle of Parcelable

Serializable principle

How should candidates answer

Serialization is the process of converting an object's state information into a form that can be stored or transmitted. During serialization, an object writes its current state to temporary or persistent storage. Later, the object can be recreated by reading or deserializing the object's state from the store. Serializable is a serialization mechanism provided by Java, while Parcelable is a serialization method provided by Android that is suitable for in-memory transmission.

Serializable

Serializable is a serialization interface provided in Java, but this interface does not have any methods that need to be implemented by implementers.

public interface Serializable {
    
    
}

This means that knowledge of the Serializable interface is used to identify that the current class can be serialized and deserialized.

basic use

Class objects that implement the Serializable interface can write serialized data to the stream through ObjectOutputStream, because Java IO is a decorator pattern, so you can write data to a file by wrapping FileOutStream through ObjectOutStream or wrapping ByteArrayOutStream to write data into memory. You can also read data from disk or memory through ObjectInputStream and then convert it into a specified object (deserialization).

try {
    
    
	TestBean serialization = new TestBean("a","b");
    //序列化
	ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("/path/xxx"));
	os.writeObject(serialization);
	//反序列化
	ObjectInputStream is = new ObjectInputStream(new FileInputStream("/path/xxx"));
	TestBean deserialization = (TestBean) is.readObject();
} catch (IOException e) {
    
    
	e.printStackTrace();
}

In addition to the basic data type, that is, the reference type, the member properties of the class that implements the Serializable interface also need to implement the Serializable interface, otherwise an exception will be thrown during serialization java.io.NotSerializableException.

public class TestBean implements Serializable {
    
    

    private String name;
    private String pwd;
    //Gson未实现Serializable接口,TestBean实例对象在序列化时抛出NotSerializableException
    private Gson gson = new Gson();
    public TestBean(String name, String pwd) {
    
    
        this.name = name;
        this.pwd = pwd;
    }

    public TestBean() {
    
    
    }

    public String getName() {
    
    
        return name;
    }

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

    public String getPwd() {
    
    
        return pwd;
    }

    public void setPwd(String pwd) {
    
    
        this.pwd = pwd;
    }

}

Therefore, if you need to serialize a certain class, you can use the transient keyword to declare properties that do not need to be serialized and deserialized in the class .

private transient Gson gson = new Gson();
serialVersionUID

In a class that implements the Serializable interface, a serialVersionUID attribute should be defined for this class:

private static final long serialVersionUID = 1L; 

Although the program is not defined, it can still run normally. However, the Java serialization mechanism is to verify that the version is consistent by judging the serialVersionUID of the class.

During the serialization operation, the serialVersionUID of the current class will be written into the serialized file. When deserializing, the system will automatically detect the serialVersionUID in the file to determine whether it is consistent with the serialVersionUID in the current class. If the consistency indicates that the version of the serialized file is the same as the version of the current class, the deserialization can be successful, otherwise it will fail.

For example, in program A, the serialVersionUID of the TestBean class is 1L, while in program B, the serialVersionUID of the TestBean class is 2L. Then the data serialized and output by program A cannot be deserialized into a TestBean object in program B.

Parcelable

Parcelable is the serialized interface provided by Android. Compared with Java's Serializable, the use of Parcelable is slightly more complicated:

public class TestBean implements Parcelable {
    
    

    private String name;
    private String pwd;
    
    public TestBean(String name, String pwd) {
    
    
        this.name = name;
        this.pwd = pwd;
    }

    public TestBean() {
    
    
    }

    public int describeContents() {
    
    
    	return 0;
    }
    //序列化
	public void writeToParcel(Parcel out, int flags) {
    
    
		out.writeString(name);
         out.writeString(pwd);
	}
    public static final Parcelable.Creator<TestBean> CREATOR 
        = new Parcelable.Creator<TestBean>(){
    
    
        	public TestBean createFromParcel(Parcel in) {
    
    
				return new TestBean(in);
			}

			public MyParcelable[] newArray(int size) {
    
    
				return new TestBean[size];
			}
    }
    private TestBean(Parcel in) {
    
    
        // 反序列化:按序列化顺序读取
		name = in.readString();
		pwd = in.readString();
    }
}

The implementation class of the Parcelable interface writes and restores data through Parcel, and must have a non-empty static variable CREATOR.

Parcel

Parcel is actually a data carrier that can write serialized data into a shared memory. Other processes can read byte streams from this shared memory through Parcel and deserialize them into objects.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-mbJWICkG-1686553360030)(images\parcel.png)]

Parcel can read and write primitive data types, and can also read and write Parcelable objects.

Therefore, the principle of Parcelable serialization is to decompose a complete object, and each part of the decomposed part is a basic data type or other types that implement Parcelable/Serializable, so as to realize the function of passing objects.

the difference

Both Parcelable and Serializable implement serialization and can use Intent for data transfer in Android. Serializable is the implementation method of Java. During the implementation process, there will be frequent IO operations, but the implementation method is simple. Parcelable is a method provided by Android, which is more efficient (it is claimed to be 10 times faster than Serializable), but it is more complicated to implement.

If you only need to transfer data in memory, you should choose Parcelable for serialization, and you should choose Serializable if you need to store it on the device or network transmission. This is because Parcelable data rules may be different in different versions of Android, so it is not recommended to use Parcelable for data persistence.

More detailed explanations of interview questions can be obtained for free by scanning the QR code!

Guess you like

Origin blog.csdn.net/Misdirection_XG/article/details/131169063