In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article focuses on "how to remove elements from List". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to remove elements from List.
I. exception code
Let's take a look at this code first. Have you ever written similar code?
Public static void main (String [] args) {
List list = new ArrayList ()
System.out.println ("start adding element size:" + list.size ())
For (int I = 0; I
< 100; i++) { list.add(i + 1); } System.out.println("元素添加结束 size:" + list.size()); Iterator iterator = list.iterator(); while (iterator.hasNext()) { Integer next = iterator.next(); if (next % 5 == 0) { list.remove(next); } } System.out.println("执行结束 size:" + list.size()); } 「毫无疑问,执行这段代码之后,必然报错,我们看下报错信息。」 我们可以通过错误信息可以看到,具体的错误是在checkForComodification 这个方法产生的。 二、ArrayList源码分析 首先我们看下ArrayList的iterator这个方法,通过源码可以发现,其实这个返回的是ArrayList内部类的一个实例对象。 public Iterator iterator() { return new Itr(); } 我们看下Itr类的全部实现。 private class Itr implements Iterator { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; Itr() {} 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 ()
}
}
@ Override
@ SuppressWarnings ("unchecked")
Public void forEachRemaining (Consumer
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.