java 请问has NextDoublenextnextint怎样用

java 请问has NextDoublenextnextint怎样用,第1张

(一)List的遍历方法及如何实现遍历删除

我们造一个list出来,接下来用不同方法遍历删除,如下代码:

List<String> list= new ArrayList<String>();famousadd("zs");famousadd("ls");famousadd("ww");famousadd("dz");

1、for循环遍历list:

for(int i=0;i<listsize();i++){if(listget(i)equals("ls"))listremove(i);}

这是一种很常见的遍历方式,但是使用这种遍历删除元素会出现问题,原因在于删除某个元素后,list的大小发生了变化,而你的索引

也在变化,所以会导致你在遍历的时候漏掉某些元素。比如当你删除第一个元素后,继续根据索引访问第二个元素后,因为删除的原因,

后面的元素都往前移动了以为,所以实际访问的是第三个元素。因此,这种遍历方式可以用在读取元素,而不适合删除元素。

2、增强for循环:

for(String x:list){if(xequals("ls"))listremove(x);}

这也是一种很常见的遍历方式,但是使用这种遍历删除元素也会出现问题,运行时会报ConcurrentModificationException异常

其实增强for循环是java语法糖的一种体现,如果大家通过反编译得到字节码,那么上面这段代码的内部实现如下所示:

for(Iterator<String> it = listiterator();ithasNext();){String s = itnext();if(sequals("madehua")){listremove(s);}}

下面就解释为什么会报ConcurrentModificationException异常。分析Iterator的源代码,重点分析整个调用该过程中的

函数(hasNext和remove):

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; // size为集合中元素的个数 } public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayListthiselementData; if (i >= elementDatalength) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; } / 此方法并没被调用,只是调用Listremove方法 public void remove() { checkForComodification(); try { ArrayListthisremove(lastRet); // size字段减1 cursor = lastRet; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } / final void checkForComodification() { // 检查修改和当前版本号是否一致,不一致则抛出异常 if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } // Listremove @Override public boolean remove(Object object) { Object[] a = array; int s = size; if (object != null) { for (int i = 0; i < s; i++) { if (objectequals(a[i])) { Systemarraycopy(a, i + 1, a, i, --s - i); a[s] = null; // Prevent memory leak size = s; modCount++; // 核心代码:修改了版本号。这样当checkForComodification的时候,modCount值就和expectedModCount不同 return true; } } } else { for (int i = 0; i < s; i++) { if (a[i] == null) { Systemarraycopy(a, i + 1, a, i, --s - i); a[s] = null; // Prevent memory leak size = s; modCount++; return true; } } } return false; }

接下来梳理一下流程,这时候你就会发现这个异常是在next方法的checkForComodification中抛出的。抛出的原因是

modCount !=expectedModCount。这里的modCount是指这个list对象从呢我出来到现在被修改的次数,当调用list

的add或者remove方法的时候,这个modCount都会自动增减;iterator创建的时候modCount被复制给了

expectedModcount,但是调用list的add和remove方法的时候不会同时自动增减expectedModcount,这样就导致

两个count不相等,从而抛出异常。大家如果理解了上面的执行流程,以后碰到类似这种问题,比如如果删除的是倒数

第二个元素却不会碰到异常。就会知道为什么了。

3、iterator遍历删除:

Iterator<String> it = listiterator();while(ithasNext()){String x = itnext();if(xequals("del")){itremove();}}

这种方式是可以正常遍历和删除的。但是你可能看到上面代码感觉和增强for循环内部实现的代码差不多,其实差别就在于上面使用

一个使用listremove(),一个使用itremove()。

(二)HashMap的遍历删除及如何实现遍历删除

一样我们先造一个hashmap出来,如下:

private static HashMap<Integer, String> map = new HashMap<Integer, String>();; public static void main(String[] args) { for(int i = 0; i < 10; i++){ mapput(i, "value" + i); } }

1、第一种遍历删除:

for(MapEntry<Integer, String> entry : mapentrySet()){Integer key = entrygetKey();if(key % 2 == 0){Systemoutprintln("To delete key " + key);mapremove(key);Systemoutprintln("The key " + + key + " was deleted");}

这种遍历删除依旧会报ConcurrentModificationException异常,

2、第二种遍历删除:

Set<Integer> keySet = mapkeySet(); for(Integer key : keySet){ if(key % 2 == 0){ Systemoutprintln("To delete key " + key); keySetremove(key); Systemoutprintln("The key " + + key + " was deleted"); } }

这种遍历删除依旧会报ConcurrentModificationException异常,

3、第三种遍历删除:

Iterator<MapEntry<Integer, String>> it = mapentrySet()iterator();while(ithasNext()){MapEntry<Integer, String> entry = itnext();Integer key = entrygetKey();if(key % 2 == 0){ Systemoutprintln("To delete key " + key); itremove(); Systemoutprintln("The key " + + key + " was deleted");}}

这种遍历是OK的

分析上述原因,如果大家理解了List的遍历删除,那么感觉HashMap的遍历删除是不是有类似之处啊。下面就分析一下原因:

如果查询源代码以上的三种的删除方式都是通过调用HashMapremoveEntryForKey方法来实现删除key的 *** 作。

在removeEntryForKey方法内知识一场了key modCount就会执行一次自增 *** 作,此时modCount就与expectedModCOunt不一致了

,上面三种remove实现中,只有第三种iterator的remove方法在调用完removeEntryForKey方法后同步了expectedModCount值与

modCount相同,所以iterator方式不会抛出异常。最后希望大家遇到问题到查询源代码,它会给你最好的解释!

it应该是一个Iterator, javalangIllegalStateException出现是因为当Iterator执行remove方法时,如果迭代器尚未调用 next 方法,或者在上一次调用 next 方法之后已经调用了 remove 方法,那么再次调用remove方法时就会抛出该异常,很显然当这段代码中的第二个while循环,也就是while(it1hasNext()){ }中,如果循环一次以上并且正好2次或2次以上满足了 ruleequals("0") 这个条件的话,那么itremove()就会执行2次,但是这时实际上itnext()只执行了一次,所以就出现上面说的那个异常,解决办法就是在外面加个判断remove是否已经执行的flag,如果在第2个while循环中已经执行一次的话,那么以后就不需要在执行remove方法,解决办法:

boolean removed;// 判断用removeFlag

while(ithasNext()){

BtcOperatorinfo operatorinfo = (BtcOperatorinfo)itnext();

removed = true;// 因为执行了next()方法,所以此时可以执行remove方法

if(operatorinfogetSorgid()equals(operinfogetSorgid())){

List optruleList = thisbtcOptruleDaofindBySoperator(operatorinfogetSoperator());

Iterator it1 = optruleListiterator();

while(it1hasNext()){

BtcOptrule optrule=(BtcOptrule)it1next();

String rule = optrulegetSruleid();

if((ruleequals("0") && removed)){ //判断remove是不是已经被执行

//thisoperatorinfolistremove(operatorinfo);

itremove();

removed = false;//防止remove再次被执行

}

}

}

}

hasNextXXX一般都是返回的布尔值,而nextInt这样的就是确确实实的返回一个值比如:

迭代器代码:Iterator it = listiterator();

while(ithasNext)

{

Systemoutprintln(itnext());

}

意思就是,当it这个变量有下一条记录的时候(ithasNext返回true的时候),打印it这个变量所包含的下一条的内容(itnext指的是放在it中的变量的值)

//方法很多,1楼是最小改动。

public static void main(String[] args) {

//将这几个变量改为Map。String line1, line2, line3, line4, line5;

Map map = new HashMap();

//定义一个计数器变量

int index=0;

String str = String str = "<row type=\"singletextline\" caption=\"Name\" ID=\"123\" CurrentValue=\"1\" others=\"width=10\"/>" ;

        int idx = strindexOf("\"") ;

        int nextIdx = strindexOf("\"", idx + 1) ;

        while( idx!=-1 && nextIdx!=-1 ) {

            //这里用"line"+index做为map的key

            mapput("line"+index,strsubstring(idx +1 , nextIdx  ))

            //计数器递增

            index++;

            //Systemoutprintln( strsubstring(idx +1 , nextIdx  )  ) ;

            idx = strindexOf("\"",nextIdx +1 ) ;

            nextIdx = strindexOf("\"", idx +1 ) ;

        }

        //这里遍历map

        for(Iterator it = mapentrySet()iterator();ithasNext();){

            MapEntry entry = itnext();

            Systemoutprintln(entrygetKey()+"="entrygetValue()) ;

        }

    }

import javautil;

public class HashSetTest {

public static void main(String[] args) {

HashSet<Car> carSet=new HashSet<>();

String[] crr= {"黑色","白色","红色","绿色","蓝色"};

for(int i=0;carSetsize()<5;) {

carSetadd(new Car(crr[i++],((i+1000)(Mathround(Mathrandom()5+1))+00),(i+1)2));

}

for(Iterator<Car> it=carSetiterator();ithasNext();) {

Systemoutprintln(itnext());

}

}

}

class Car implements Comparable<Car>{

private String color;//颜色!

private Double weight;//重量

private Integer number;//轮子个数!

public Car(String color, Double weight, Integer number) {

super();

thiscolor = color;

thisweight = weight;

thisnumber = number;

}

public Integer getNumber() {

return number;

}

public int compareTo(Car c) {

return Integercompare(cgetNumber(), thisnumber);

}

public int hashCode() {

return thisnumber;

}

public boolean equals(Object obj) {

if(!(obj instanceof Car))return false;

Car c=(Car)obj;

return cnumber==thisnumber;

}

public String toString() {

return "颜色:"+color+"\t重量:"+weight+"\t轮胎:"+number+"个";

}

}

以上就是关于HashMap和List遍历方法总结及如何遍历删除全部的内容,包括:HashMap和List遍历方法总结及如何遍历删除、java.lang.IllegalStateException、java 请问has NextDouble/next/nextint怎样用等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/8773722.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-21
下一篇 2023-04-21

发表评论

登录后才能评论

评论列表(0条)

保存