【问题标题】:In Java, what's the difference between HashSet<Integer> = new HashSet(2) and HashSet<Integer> = new HashSet<Integer>(2)?在 Java 中,HashSet<Integer> = new HashSet(2) 和 HashSet<Integer> = new HashSet<Integer>(2) 有什么区别?
【发布时间】:2014-04-15 01:28:07
【问题描述】:

使用初始化有什么区别

HashSet<Integer> s = new HashSet(2) 

HashSet<Integer> s = new HashSet<Integer>(2)

?

【问题讨论】:

  • 9 个字符,除非您输入一些空格。 (实际上 HashSet 没有分配给它的成员类型,因此 new HashSet() 是“通用捐助者”,可以分配给任何成员类型的 HashSet 引用。)

标签: java syntax types casting initialization


【解决方案1】:

唯一的区别是第一个会给你一个关于原始类型'HashSet'的编译器警告。

【讨论】:

    【解决方案2】:

    有趣的是,用 javac 1.7.0_07 编译:

    编译时带有未经检查的警告 --

    HashSet<Integer> s0 = new HashSet(2);
    

    编译时没有消息--

    HashSet<Integer> s1 = new HashSet<>(2);
    HashSet<Integer> s2 = new HashSet<Integer>(2);
    

    【讨论】:

    • 完全符合您的预期。有什么好玩的?
    • @EJP - 好吧,new HashSet(2)new HashSet&lt;&gt;(2) 之间存在毫无意义的区别。
    猜你喜欢
    • 2012-08-15
    • 2012-09-24
    • 2014-12-30
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多