JAVA(小技巧--List)
1:List數(shù)據(jù)的動(dòng)態(tài)刪除
在開發(fā)的過程中經(jīng)常遇到需要?jiǎng)討B(tài)刪除List數(shù)據(jù)的要求,開始打算用下標(biāo)for循環(huán)。
因?yàn)長ist是動(dòng)態(tài)變化的,所以下標(biāo)的值和List的長度也是變化的,循環(huán)判斷的時(shí)候需要對for的循環(huán)變量和循環(huán)次數(shù)重新計(jì)算。
例子如下:
??????? List<String> lists = new ArrayList<String>();
??????? for (int i=0; i<6; i++){
??????????? lists.add(String.valueOf(i));
??????? }
?????? // 添加數(shù)據(jù)打印出0,1,2,3,4,5
??????? for (String obj:lists ){
??????????? System.out.println(obj);
??????? }
?????? // 刪除數(shù)據(jù)用for
??????? for (int j=0; j<lists.size(); j++){
??????????? if (lists.get(j).equals("0")) {
??????????????? lists.remove(j);
??????????????? j--;
??????????????? continue;
??????????? }
??????????? if (lists.get(j).equals("5")) {
??????????????? lists.remove(j);
??????????????? j--;
??????????? }
??????? }
?????? // 剩余數(shù)據(jù)1,2,3,4
??????? for (String obj:lists ){
??????????? System.out.println(obj);
??????? }
?后來發(fā)現(xiàn)用List的iterator進(jìn)行刪除,更加方便。代碼如下
??????? Iterator<String> iterator = lists.iterator();
??????? while(iterator.hasNext()){
??????????? String e = iterator.next();
??????????? if (e.equals("0")){
??????????????? iterator.remove();
??????????? }
??????????? if (e.equals("5")){
??????????????? iterator.remove();
??????????? }
??????? }
?
轉(zhuǎn)載于:https://www.cnblogs.com/lucongrui/p/3564603.html
總結(jié)
以上是生活随笔為你收集整理的JAVA(小技巧--List)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android菜鸟的成长笔记(13)——
- 下一篇: 【转】 SED多行模式空间