加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java泛型?

发布时间:2020-12-15 02:05:45 所属栏目:Java 来源:网络整理
导读:多年来我看到很多人都使用“泛型”这个词,老实说我不知道??它意味着什么,不管它是什么我最有可能使用它但只是不知道它被称为那个. :p 解决方法 从 http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html起 Generics provides a way for you to
多年来我看到很多人都使用“泛型”这个词,老实说我不知道??它意味着什么,不管它是什么我最有可能使用它但只是不知道它被称为那个. :p

解决方法

从 http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html起

Generics provides a way for you to communicate the type of a collection to the compiler,so that it can be checked. Once the compiler knows the element type of the collection,the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection.

Here is a simple example taken from the existing Collections tutorial:

// Removes 4-letter words from c. Elements must be strings
    static void expurgate(Collection c) {
        for (Iterator i = c.iterator(); i.hasNext(); )
          if (((String) i.next()).length() == 4)
            i.remove();

}

Here is the same example modified to use generics:

// Removes the 4-letter words from c
    static void expurgate(Collection<String> c) {
        for (Iterator<String> i = c.iterator(); i.hasNext(); )
          if (i.next().length() == 4)
            i.remove();

}

对不起直接c& p,但我发现这个写作比我写的更好.

编辑以在评论中包含一个好点:

Generics are not limited to communicating the type of a collection to the compiler…the collections library just happened to be a good way to demonstrate them.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读