Java泛型? [英] Java Generics?

查看:100
本文介绍了Java泛型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

多年来,我看到许多人使用泛型这个词,我真的不知道它的意思,不管它是我最有可能使用它,但不知道它被称为那个。 :p

解决方案

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


泛型为您提供了一种将集合的类型传递给编译器的方法,以便可以对其进行检查。一旦编译器知道集合的元素类型,编译器就可以检查你是否一直使用集合,并且可以在集合中取出的值上插入正确的强制转换。



<这是一个从现有集合教程中取得的简单示例:



  //删除4来自c的字母单词。 (Iterator i = c.iterator(); i.hasNext();)
if(((String)i。 next())。length()== 4)
i.remove();


code


lockquote

这里是相同的例子修改为使用泛型:



  //从c $ b $中移除4个字母的单词(Iterator< String> i = c.iterator(); i.hasNext();)
if(i.next()。length ()== 4)
i.remove();

}

对不起,我发现这个写出来比我能写的要好。



编辑包括评论中的一个优点:$ b​​
$ b < blockquote>

泛型不限于
将集合
的类型传递给编译器......集合
库恰好是一个好东西
来展示它们。



Over the years I seen many people use the word "generics", I honestly have not a clue what it means, whatever it is I most likely use it but just don't know that it was called that. :p

解决方案

From 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();

}

Sorry for the direct c&p but I found that this write up was better than something I could have written.

Edit to include a good point made in the comments:

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.

这篇关于Java泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆