集册 Java实例教程 实现Cloneable接口以创建Cloneable类

实现Cloneable接口以创建Cloneable类

欢马劈雪     最近更新时间:2020-01-02 10:19:05

524
实现Cloneable接口以创建Cloneable类

import java.util.*;
/** from 
nowjava.com - 时  代  Java**/


class Stack2<T> implements Cloneable {

    private ArrayList<T> items;

    private int top = 0;


    public Stack2() {

        items = new ArrayList<T>();

    }


    public void push(T item) {

        items.add(item);

        top++;

    }


    public T pop() {/*来 自 时 代 J a v a 公 众 号 - N o w J a v  a . c o m*/

        if (items.size() == 0)

            throw new EmptyStackException();

        T obj = items.get(--top);

        return obj;

    }


    public boolean isEmpty() {

        if (items.size() == 0)

            return true;

        else

            return false;

    }


    protected Stack2<T> clone() {

        try {

            Stack2<T> s = (Stack2<T>) super.clone(); //Clone the stack.

            s.items = (ArrayList<T>) items.clone(); //Clone the list.

            return s; // Return the clone

        } catch (CloneNotSupportedException e) {

            //This shouldn't happen because Stack is Cloneable.

            throw new InternalError();

        }

    }

}

public class StackTest2 {

    public static void main(String[] args) {

        Stack2<String> s = new Stack2<String>();

        s.push("hi");

        s.push("hello");

        s.push("good day");

        Stack2<String> s2 = s.clone();

        System.out.format("%s%n", s.pop());

        System.out.format("%s%n", s.pop());

        System.out.format("%s%n", s.pop());

        System.out.format("%s%n", s2.pop());

    }

}

展开阅读全文