译文

Java谜题选 - II

翻译:易晓斓 | 2007-08-24 10:17:08 | 阅读2664 | 来源

题目2:关于Sets的更多Fun。

对了,这个题目表面上看也是关于Sets的...

程序

import  java.net.*;
public class UrlSet {
    private static final String[] URL_NAMES = {
       "http://javapuzzlers.com",
       "http://apache2-snort.skybar.dreamhost.com",
       "http://www.google.com",
       "http://javapuzzlers.com",
       "http://findbugs.sourceforge.net",
       "http://www.cs.umd.edu"
      };

    public static void main (string[] args)
                   throws MalformedURLException {
          Set<URL> favorites = new HashSet<URL>();
          for (String urlName : URL_NAMES)
                favorites.add(new URL(urlName));
           System.out.println(favorites.size());
    }
}

答案

(a) 4
(b) 5
(c) 6
(d) None of the above

请大家想想,踊跃发表意见。答案和分析之后发布。谢谢。

【本文翻译仅为外语学习及阅读目的,原文作者个人观点与译者及译言网无关】

分享:

本文共有10 条评论:

1楼 twg 评论于 2007-08-24 11:42:24

选择 D

2楼 yzx110 评论于 2007-08-24 12:13:42

D吧
java不太熟悉,不过我才像Set之类的也肯定是
批量分配存储空间的,那么size可能初始化就比6大了。
代码没问题么?
Set<URL> favorites = new HashSet<URL>$$
不该写成
Set<URL> favorites = new HashSet<URL>()$$???

3楼 foreverclq 评论于 2007-08-24 12:44:54

刚开始偶还以为是6呢,run一下才知道,嘿嘿
josh 构造那两个URL 还真有心机 哈哈

btw,Google video 偶看不了, 楼主是用代理吗?

4楼 sinceresin 评论于 2007-08-24 12:46:25

a

5楼 vole 评论于 2007-08-24 22:39:08

竟然是a,以为是bug,看了代码才知道是这样处理null的
可是我ping了http://javapuzzlers.com,竟然可以ping通的。。

6楼 foreverclq 评论于 2007-08-26 21:34:41

和null无关的,和set有关的是hash,还是hash...
哈哈

7楼 vole 评论于 2007-08-27 15:53:54

hashCode要一样,然后还要equals哦

8楼 HiugongGwok 评论于 2007-08-27 17:07:11

这个太阴了,明明是URL的实现有问题。实现URL的人破坏了hashCode、equals的契约。当然当初写URL类的时候Josh还没写他那本Effective Java,大家都没重视这个问题。

9楼 sohochaser 评论于 2007-10-07 22:35:16

将main改了一下:

public static void main (String[] args)
throws MalformedURLException {
Set<URL> favorites = new HashSet<URL>()$$
for (String urlName : URL_NAMES)
{
System.out.print(favorites.add(new URL(urlName)))$$
System.out.println("-> "+urlName)$$
}
System.out.println(favorites.size())$$
}

输出:

true-> http://javapuzzlers.com
false-> http://apache2-snort.skybar.dreamhost.com
true-> http://www.google.com
false-> http://javapuzzlers.com
true-> http://findbugs.sourceforge.net
true-> http://www.cs.umd.edu
4


false-> http://apache2-snort.skybar.dreamhost.com 这个错什么原因啊?是dreamhost的原因吗?保留字?改成dreamhostt就没有问题了

10楼 易晓斓 评论于 2007-10-08 00:53:15

sohochaser, 你读一下我的谜题答案就明白了。

添加评论