标记接口(Marker interface)

标记接口没有具体实现

RandomAccess接口

实现此类的接口支持快速随机访问,源码大意:

(1)给List接口实现类使用的标志接口,目的是使其支持(在恒定时间内)的快速随机访问

(2)推荐在遍历集合的时候检查该List接口是否实现了RandomAccess接口,以便让不同的集合使用更优的遍历算法(如 ArrayList用for循环遍历快一些,LinkedList用迭代器遍历快一些)

(3)通常来说,如果一个List用for循环遍历比用迭代器遍历的速度快,那么推荐实现RandomAccess接口

在Collections工具类的二分查找中有具体的区分实现

 

 通常情况下,实现此类的接口,底层的存储一般用数组,比如ArrayList,并且普通的for循环遍历更优一些

java.io.Serializable接口

序列化指的是把对象转化成字节序列的过程,就是把内存中的对象转换成一连串的字节bytes描述的过程

反序列化就是将字节bytes数据恢复为对象的过程

jdk源码注释

实现了Serializable接口的类(以及它的子类)可以进行序列化、反序列化,反之未实现的不可以

如果一个Serializable类没有明确指定serialVersionUID值,序列化过程时会自动计算出一个值并赋值。

但强烈建议明确指定,因为该值的计算和编译器的实现有关,否则反序列化时有可能抛出InvalidClassException;并且同样强烈建议使用private修饰,因为该值不是用来继承的

Cloneable接口

 源码注释主要翻译:

/**
 * A class implements the <code>Cloneable</code> interface to
 * indicate to the {@link java.lang.Object#clone()} method that it
 * is legal for that method to make a
 * field-for-field copy of instances of that class.
 * <p>
 * Invoking Object's clone method on an instance that does not implement the
 * <code>Cloneable</code> interface results in the exception
 * <code>CloneNotSupportedException</code> being thrown.
 * <p>
 * By convention, classes that implement this interface should override
 * <tt>Object.clone</tt> (which is protected) with a public method.
 * See {@link java.lang.Object#clone()} for details on overriding this
 * method.
 * <p>
 * Note that this interface does <i>not</i> contain the <tt>clone</tt> method.
 * Therefore, it is not possible to clone an object merely by virtue of the
 * fact that it implements this interface.  Even if the clone method is invoked
 * reflectively, there is no guarantee that it will succeed.
 *
 * @author  unascribed
 * @see     java.lang.CloneNotSupportedException
 * @see     java.lang.Object#clone()
 * @since   JDK1.0
 */

1、一个类实现了Cloneable接口,那么这个类的对象就可以合法的调用Object.clone()方法(在编码时写的super.clone()),来进行字段到字段的复制来克隆出另一个对象

2、如果一个类没有实现Cloneable接口,那么这个类的对象在调用Object.clone()时会抛出CloneNotSupportedException

3、按照规定,实现了Cloneable接口的类应用public访问符重写Object.clone()方法

4、注意,该接口不包含clone()方法,因此不能仅仅根据某个类实现了这个接口,就能克隆出一个对象(就是说还是要重写clone()),即使调用了clone(),也不保证会调用成功

总结下就是:如果想通过一个对象复制出另一个对象,又不想一个一个字段的复制,就让这个对象实现Cloneable接口,重写clone()方法

注意深拷贝和浅拷贝

针对的都是包含引用类型属性的对象,拷贝的都是栈里面的变量数据

浅拷贝:clone的对象和原对象相比,各个属性具有相同给的值,但引用的对象(引用类型的那些属性)和原对象的引用对象指向相同的堆地址(更改任意一个,另一个也会改变)

深拷贝:clone的对象和原对象相比,各个属性,以及引用类型属性,都会克隆一遍,两者完全独立

posted @ 2022-06-29 15:12  鼠标的博客  阅读(351)  评论(0编辑  收藏  举报