Summary of some problems when the set stores URLs and URL Problems
Let's take a look at the question first:
package com.lk.C;import java.net.MalformedURLException;import java.net.URL;import java.util.HashSet;import java.util.Set;public class Test3 { private static final String [] URLNAMES = { "http://www.sina.com",//202.108.33.94 "http://www.nuw.edu.cn",//124.115.173.252 "http://javapuzzlers.com",//208.97.154.9 "http://www.google.com",//64.233.189.147 "http://Javapuzzlers.com",//208.97.154.9 "http://apache2-snort.skybar.dreamhost.com"//208.97.154.9 }; public static void main(String[] args) throws MalformedURLException { // TODO Auto-generated method stub Set<URL> favorites = new HashSet<URL>(); for(String urlName : URLNAMES){ favorites.add(new URL(urlName)); } System.out.println(favorites.size()); }}
What is output?
Answer:
4 is output when the network is connected, because the equals method of the URL is compared. According to the equals documentation, if the two host names can be resolved to the same IP address, the two hosts are considered to be the same (even if the host names are different); if one host name cannot be resolved, however, if the two host names are the same (case-insensitive), or both are null, they are also considered to be the same.
That is to say, if the IP addresses of the two URLs are the same, the two URLs are equal.
If the IP address cannot be resolved when the network is disconnected, the URL name must be determined. Only the URL with the same name is considered to be the same (case-insensitive), so the output is 5.
Therefore, do not replace the URL application with the key of Set and Map. You can use URI instead, so that there is no network problem.