开发者

How to detect if URL object points to same path as another URL object in Collection

I need to write something like this:

private Set processedLinks = new HashSet();

public boolean isProcessed(String url) throws MalformedURLException {

        return processedLinks.contains(new URL(url));
    }

This doesn't work, because created URL is another object than URL in collection. I need to compare mat开发者_StackOverflow社区ch of host and file of created URL with URLs in HashSet. What is the best way?

I wanted to extend URL with my class and override equals(), but URL is final. So the second idea I have is to make something like URLHashSet extends HashSet and override contains method. But I'm not sure if it wouldn't have negative effect to performance, because that HashSet will contains tens of thousands elements.

Do you have please some idea how to resolve this? Thanks.


I'd recommend using URI instead of URL.

URL.equals should be avoided. From the docs you will see that it requires name resolution (which is a blocking operation) and is "is known to be inconsistent with virtual hosting in HTTP". URIs make more sense because you are not actually comparing physical locations, just the identifiers.


I don't want this to come off sounding harsh, but I think your understanding of equals/hashCode is flawed.

The URL should hash out and compare identically even though the object references are two separate objects.

I would try just a simple test of creating two separate URL objects with the same string URL value.

The following tests should give you your answer:

u1 == u2 => false
u1.equals(u2) => true
u2.equals(u1) => true
u1.hashCode() == u2.hashCode() => true

Unless my understanding of your problem is incorrect.


Try using the String representation of the URL object.


you can use composition instead of inheritance , like :

class MyUrl {

  private Url url;

  public boolean equals (MyUrl otherUrl) {
  }

}

and make Set of MyUrl .

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜