Iterator equals比较的逻辑误区

     public boolean equals(Object o)
        {
            Iterator iterThis;
            Iterator iterThat;
            if(!(o instanceof Map))
                break MISSING_BLOCK_LABEL_84;
            Map that = (Map)o;
            if(size() != that.size())
                return false;
            iterThis = entrySet().iterator();
            iterThat = that.entrySet().iterator();
            do
                if(!iterThis.hasNext())
                    break MISSING_BLOCK_LABEL_80;
            while(iterThis.next().equals(iterThat.next()));
            return false;
            return true;
            ConcurrentModificationException e;
            e;
            return false;
        }


可能你会很快地修正为: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
        public boolean equals(Object o) {
            Iterator iterThis;
			Iterator iterThat;
			if (o instanceof Map) {
				Map that = (Map) o;
				if (size() != that.size())
					return false;
				iterThis = entrySet().iterator();
				iterThat = that.entrySet().iterator();
				try {
					do
						if (!iterThis.hasNext())
							break;//注意此行
					while (iterThis.next().equals(iterThat.next()));
					return true;//注意此行
					
				} catch (ConcurrentModificationException e) {
					return false;
				}
			}
			return false;
		}


其实是错误的 

应该是: 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
        public boolean equals(Object o) {
            Iterator iterThis;
			Iterator iterThat;
			if (o instanceof Map) {
				Map that = (Map) o;
				if (size() != that.size())
					return false;
				iterThis = entrySet().iterator();
				iterThat = that.entrySet().iterator();
				try {
					do
						if (!iterThis.hasNext())
							return true;
					while (iterThis.next().equals(iterThat.next()));
					return false;
 
				} catch (ConcurrentModificationException e) {
					return false;
				}
			}
			return false;
		}


其中的do while可以改为以下代码,可读性比较强 

1
2
3
4
5
					while(iterThis.hasNext()){
						if(!iterThis.next().equals(iterThat.next()))
								return false;
					}
					return true;

你可能感兴趣的:(Iterator equals比较的逻辑误区)