Java: how to use clone (), and what to do with cast verification

This code:

class RawStringIterator {
        java.util.Stack<State> stateStack = new java.util.Stack<State>();
        RawStringIterator(RawStringIterator i) {
              stateStack = (java.util.Stack<State>) i.stateStack.clone();
        }
        /* ... */
}

gives me this warning:

Type safety: Unchecked cast from Object to Stack<Utils.OperatorTree.RawStringIterator.State>

I think I can ignore the warning here. But I wonder how to use it clone()at all? Do I always use @SuppressWarnings("unchecked")every time I use clone()? Or should I always do an extra extra check?

+3
source share
4 answers

If you have a choice, it is best not to use / use clone()at all, because it is a broken API . Just create / use a copy constructor.

- clone(), , Stack<T>.clone() Stack<T> Object. Java5.

:, Stack java.util.Stack, Javadoc:

LIFO Deque , .

, , ArrayDeque .

+11

. clone() Object, java.util.Stack, -.

java.util.Stack, clone() - . -.

+2

, .

( clone()), Java Generics ( FAQ!)

0

, , clone().

This is one of the reasons you can use copy constructors instead clone()if they are available.

By the way, in your code, when the constructor is used RawStringIterator(RawStringIterator i), the first initialization is stateStacknot needed:

class RawStringIterator {
    Stack<State> stateStack = new Stack<State>();
    RawStringIterator(RawStringIterator i) {
          stateStack = (Stack<State>) i.stateStack.clone();
    }
    /* ... */
}

You might want to remove this.

0
source

Source: https://habr.com/ru/post/1769726/


All Articles