题目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
请大家想想,踊跃发表意见。答案和分析之后发布。谢谢。
本文版权所有,未经许可,请勿转载
内容合作请 联系我们









Java谜题选 - II







twg 童生 | 2007年08月24日
选择 D
yzx110 童生 | 2007年08月24日
D吧
java不太熟悉,不过我才像Set之类的也肯定是
批量分配存储空间的,那么size可能初始化就比6大了。
代码没问题么?
Set<URL> favorites = new HashSet<URL>$$
不该写成
Set<URL> favorites = new HashSet<URL>()$$???
foreverclq 童生 | 2007年08月24日
刚开始偶还以为是6呢,run一下才知道,嘿嘿
josh 构造那两个URL 还真有心机 哈哈
btw,Google video 偶看不了, 楼主是用代理吗?
foreverclq 童生 | 2007年08月26日
和null无关的,和set有关的是hash,还是hash...
哈哈
vole 童生 | 2007年08月27日
hashCode要一样,然后还要equals哦
HiugongGwok 童生 | 2007年08月27日
这个太阴了,明明是URL的实现有问题。实现URL的人破坏了hashCode、equals的契约。当然当初写URL类的时候Josh还没写他那本Effective Java,大家都没重视这个问题。
sohochaser 童生 | 2007年10月07日
将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就没有问题了
易晓斓 状元 | 2007年10月08日
sohochaser, 你读一下我的谜题答案就明白了。