Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add to hashmap takes a long time

Tags:

java

I've stuck by a few lines in my java program, which take too much time (about 20s), and it seems weird to me.

Here are the lines

 Map<URL, Integer> res2 = new HashMap<>();
 for (URL url : res) {
     res2.put(url, null);
 }

Which res defined as following :

List<URL> res = new ArrayList<>();

In my program, res.size() ~= 1500

Do you have any idea of where my problem could come from ?

Thanks !

like image 504
Nisalon Avatar asked Apr 13 '13 12:04

Nisalon


1 Answers

The hashCode() method of java.net.URL performs DNS resolution. The URL class is unsuitable for use in a HashSet or as keys in a HashMap. Use either Strings or java.net.URI.

Here's some background:

  • Michael Scharf: java.net.URL.equals and hashCode make (blocking) Internet connections....
  • Eishay Smith: Java's URL little secret (which RobAu linked in a comment to this answer)
like image 133
Barend Avatar answered Oct 03 '22 17:10

Barend