首页 > 编程语言 >java -- 标记接口

java -- 标记接口

时间:2023-04-15 20:33:06浏览次数:24  
标签:java String -- age System 接口 Student public name

标记接口

标记接口(Marker Interface),又称标签接口(Tag Interface)

仅代表一个标记 不包含任何方法
标记接口是用来判断某个类是否具有某种能力

Cloneable标记接口

此类实现了 Cloneable 接口,以指示 Object.clone 方法可以合法地对该类实例进行按字段复制
如果在没有实现 Cloneable 接口的实例上调用 Object 的 clone 方法, 则会导致抛出 CloneNotSupportedException 异常

// Cloneable源码:
public interface Cloneable { }
// 仅代表一个标记

// 克隆的前提条件:
    // 被克隆的对象必须实现Cloneable接口
    // 必须重写clone方法

基本使用

public class CloneableDemo {
    public static void main(String[] args) throws CloneNotSupportedException {
        // ArrayList类实现了Cloneable接口
        ArrayList<String> list = new ArrayList<String>();
        list.add("张三");
        list.add("李四");
        list.add("王五");

        ArrayList<String> listClone = (ArrayList<String>) list.clone();
        System.out.println(list == listClone);
        System.out.println(listClone);
    }
}

Clone案例:将一个学生的数据复制到另一个学生对象中,并且两个对象不受任何的影响.

传统方式:

public class CloneTest {
    public static void main(String[] args) {
        //传统方式:
        Student stu1 = new Student("张三", 12);
        //再次创建一个新的学生对象
        Student stu2 = new Student();
        //把stu1对象name的值取出来赋值给stu2对象的name
        stu2.setName(stu1.getName());
        //把stu1对象age的值取出来赋值给stu2对象的age
        stu2.setAge(stu1.getAge());

        System.out.println(stu1 == stu2);
        System.out.println(stu1);
        System.out.println(stu2);

        System.out.println("================");
        stu1.setName("李四");
        System.out.println(stu1);
        System.out.println(stu2);
    }
}
class Student {
    private String name;
    private int age;

    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 Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Student() {
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

此时修改对象1的姓名与对象2的姓名无关

克隆方式(浅拷贝):

/*
实现Cloneable接口
重写clone方法 将访问权限改为public 并将返回值类型改为Student
*/
class Student implements Cloneable{
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public Student clone() throws CloneNotSupportedException {
        return (Student) super.clone();
    }
}
class CloneTest01 {
    public static void main(String[] args) throws CloneNotSupportedException {
        //克隆方式
        //创建学生对象
        Student stu1 = new Student("张三",12);
        //通过克隆获得一个student对象
        Student stu2 = stu1.clone();


        System.out.println(stu1 == stu2);
        System.out.println(stu1);
        System.out.println(stu2);

        stu1.setName("李四");
        System.out.println(stu1);
        System.out.println(stu2);
    }
}

浅拷贝的局限性:基本数据类型(包括String)可以达到完全复制,引用数据类型则不可以;

class Student implements Cloneable{
    private String name;
    private int age;
    private Car car;

    @Override
    public Student clone() throws CloneNotSupportedException {
        return (Student) super.clone();
    }
}

class Car {
    private String brand;

    public Car() {
    }

    public Car(String brand) {
        this.brand = brand;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    @Override
    public String toString() {
        return "Car{" +
                "brand='" + brand + '\'' +
                '}';
    }
}

class CloneTest02 {
    public static void main(String[] args) throws CloneNotSupportedException {
        //克隆方式
        //创建学生对象
        Student stu1 = new Student("张三",12,new Car("宝马"));
        //通过克隆获得一个student对象
        Student stu2 = stu1.clone();

        System.out.println(stu1 == stu2);
        System.out.println(stu1);
        System.out.println(stu2);

        stu1.setName("李四");
        //stu1获得了Car修改Car的品牌
        stu1.getCar().setBrand("奔驰");
        //浅拷贝的局限性 引用类型只是拷贝了地址值 修改一个对象的的属性 另一个也改变了
        System.out.println(stu1);
        System.out.println(stu2);
    }
}

使用深拷贝解决上述问题

//首先 Car类实现克隆接口 重写clone方法
class Car implements Cloneable {
    private String brand;

    public Car() {
    }

    public Car(String brand) {
        this.brand = brand;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    @Override
    public String toString() {
        return "Car{" +
                "brand='" + brand + '\'' +
                '}';
    }

    @Override
    protected Car clone() throws CloneNotSupportedException {
        return (Car) super.clone();
    }
}

//修改Student的clone方法
class Student implements Cloneable {
    private String name;
    private int age;
    private Car car;

    public String getName() {
        return name;
    }

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

    public Student(String name, int age, Car car) {
        this.name = name;
        this.age = age;
        this.car = car;
    }

    public Car getCar() {
        return car;
    }
    public void setCar(Car car) {
        this.car = car;
    }

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

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public Student() {
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", car=" + car +
                '}';
    }

    @Override
    public Student clone() throws CloneNotSupportedException {
//        return (Student) super.clone();
        Student student = (Student) super.clone();
        Car car = this.car.clone();
        student.setCar(car);
        return student;
    }
}

RandomAccess标记接口

List 实现所使用的标记接口,用来表明其支持快速(通常是固定时间)随机访问。此接口的主要目的是允许一般的算法更改其行为,从而在将其应用到随机或连续访问列表时能提供良好的性能
简单的来说,如果实现了这个接口,普通for循环的速度要优于增强for的速度.

public class ArrayList_Demo01 {
    public static void main(String[] args) {
        //创建ArrayList集合
        List<String> list = new ArrayList<String>();
        //添加100W条数据
        for (int i = 0; i < 1000000; i++) {
            list.add(i+"a");
        }

        //测试普通循环
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < list.size(); i++) {
            //取出集合的每一个元素
            list.get(i);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("普通循环遍历: "+(endTime-startTime));

        //测试迭代器遍历
        startTime = System.currentTimeMillis();
        //获取迭代器
        Iterator<String> it = list.iterator();
        while (it.hasNext()){
            //取出集合的元素
            it.next();
        }
        endTime = System.currentTimeMillis();
        System.out.println("迭代器遍历: "+(endTime-startTime));
    }
}

LinkedList没有实现此接口,测试:

ublic class LinkedList_Demo01 {
    public static void main(String[] args) {
        //创建LinkedList集合
        List<String> list = new LinkedList<String>();
        //添加10W条数据
        for (int i = 0; i < 100000; i++) {
            list.add(i+"b");
        }

        //测试普通遍历时间
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < list.size(); i++) {
            //取出集合的每一个元素
            list.get(i);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("普通遍历时间: "+(endTime-startTime));

        //测试迭代器
        startTime = System.currentTimeMillis();
        //获取迭代器
        Iterator<String> it = list.iterator();
        while (it.hasNext()){
            //取出集合的每一个元素
            it.next();
        }
        endTime = System.currentTimeMillis();
        System.out.println("顺序迭代器访问时间: "+(endTime-startTime));
    }
}

实际应用

public class Test {
    public static void main(String[] args) {
        //我们今后可能有的集合不是直接创建的 可能是别人传递的
        //我们看到的就是一个List接口
        //至于具体的实现类可能不清楚
        List<String>  list = new ArrayList<>();

        //list = new LinkedList<>();
        //我们可以判断以下 这个list集合是否实现了RandomAccess接口
        //如果实现了 可以使用随机访问的方式来进行遍历
        //如果没实现 可以使用迭代器的方式来进行遍历 这样可以提高效率
        if(list instanceof  RandomAccess){
            for (int i = 0; i < list.size(); i++) {
            }

        }else {
            for (String s : list) {

            }
        }
    }
}

标签:java,String,--,age,System,接口,Student,public,name
From: https://www.cnblogs.com/paopaoT/p/17321793.html

相关文章

  • https://blog.csdn.net/Slade99X/article/details/119790716
    https://blog.csdn.net/Slade99X/article/details/119790716https://blog.csdn.net/challenglistic/article/details/129556054https://blog.csdn.net/u011215927/article/details/108206559......
  • Rust语言 学习10 测试
    一、编写测试cargo创建测试项目使用Clion打开工程,lib.rs代码如下然后运行这个测试看看效果增加一个单测#[test]fnnew_test(){panic!("maketestfail");}......
  • bash $$
    在bash中,$$是一个特殊变量,它代表当前正在执行的进程的PID(进程ID)。可以在脚本中使用$$来访问当前进程的PID。例如,要输出当前进程的PID,可以使用以下命令:echo$$这将输出当前进程的PID。......
  • mongoDB 4.2:赋能未来数据应用的智慧之选
    mongoDB是在2019年发布,具体特性如下图:1.FullTextSearchMongoDB4.2之前,全文搜索(FullTextSearch)的能力是靠TextIndex来支持的,在MongoDB-4.2里,MongoDB直接与Lucene等引擎整合,在Atlas服务里提供全文建索的能力。2.MongoDBFTS原理1.用户可以在Atlas上,对集合开启全......
  • OpenCV图像腐蚀与膨胀(13)
    膨胀与腐蚀是数学形态学在图像处理中最基础的操作。其卷积操作非常简单,对于图像的每个像素,取其一定的邻域,计算最大值/最小值作为新图像对应像素位置的像素值。其中,取最大值就是膨胀,取最小值就是腐蚀。膨胀与腐蚀能实现多种多样的功能,主要如下:消除噪声分割出独立的图像元素,在图像中......
  • kuangbin专题一 简单搜索 起火迷宫(UVA-11624)
    Fire!DescriptionJoeworksinamaze.Unfortunately,portionsofthemazehavecaughtonfire,andtheownerofthemazeneglectedtocreateafireescapeplan.HelpJoeescapethemaze.GivenJoe’slocationinthemazeandwhichsquaresofthemazeareo......
  • js 异步任务执行顺序问题
    js是单线程的(非阻塞的),实现方法就是事件循环;分同步任务和异步任务;newPromise((resolve,reject)=>{resolve(1)console.log('log1')}).then(()=>{console.log('log2')})console.log('log3')setTimeout(()=>......
  • fastdds学习之2——Helloworld Demo
    本节详细介绍了如何使用C++API一步一步地创建一个简单的FastDDS应用程序,其中包含发布者和订阅者。也可以使用eProsimaFastDDSGen工具自行生成与本节中实现的示例类似的示例。在构建发布/订阅应用程序中解释了这种额外的方法,本例程在eProsimaFastDDSGithub仓库中,环境搭建完成......
  • Debian11 修改时区
    首先需要明白中国在东八区,即UTC+8。以上海为例:timedatectlls-l/etc/localtimetimedatectllist-timezonesunlink/etc/localtimesudotimedatectlset-timezoneAsia/Shanghailn-s/usr/share/zoneinfo/Asia/Shanghai/etc/localtime ......
  • 代码块
    代码块代码块是什么代码块就是构造器的补充,又被叫做初始代码块,是类的成员之一,类似于方法,将逻辑语句包起来但又跟方法不同,没有方法名,没有返回值,没有参数,只有方法体,而且不需要通过对象来调用或类显示调用代码块的书写格式(修饰符){代码};注意事项:修饰符可以选,但也只能......