Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
        }
    }
like image 960
andyqee Avatar asked Dec 06 '25 20:12

andyqee


1 Answers

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.

like image 159
Bhesh Gurung Avatar answered Dec 08 '25 09:12

Bhesh Gurung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!