andyqee
andyqee

Reputation: 3221

what can we benefit from using "@SuppressWarnings("unchecked")" in java?

When i read the the jdk source code,i find the annotation,but i am not sure why it was used here?
what can we benefit from using "@SuppressWarnings("unchecked")" in java?
when should we use it,and why?
Sample code from jdk source code

  private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor != size;
        }

        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

Upvotes: 3

Views: 6954

Answers (1)

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

It's there to suppress the warning generated by (E) elementData[lastRet = i], which for the compiler is type unsafe. The compiler can not garauntee that the casting will succeed at runtime.

But since the the person who wrote the code knew that it was always going to be safe, decided to use @SuppressWarnings("unchecked") to suppress the warning at compilation.

I use it mostly when I am sure that it is going to be safe because it makes my code look cleaner on my Ecplise IDE.

Upvotes: 9

Related Questions