< E>是什么? Java语法是什么意思? [英] What does the <E> syntax mean in Java?

查看:133
本文介绍了< E>是什么? Java语法是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经快速搜索了一个答案,但无法找到/想到准确的搜索参数。

I've quickly googled for an answer but could not not find/think of accurate search parameters.

我正在自学Java,但似乎无法找到某种语法的含义。

I am teaching myself Java, but can't seem to find the meaning of a certain syntax.

public class Node<E>{
    E elem;
    Node<E> next, previous;
}

< E> 表示?我依稀记得箭头括号与矢量有关但是基于上面的代码我感觉它与枚举有关。

What does the <E> signify? I vaguely remember the arrow braces having something to do with vectors but based on the code above I get the feeling it has to do with enumerations.

任何帮助或澄清都是非常感激。谢谢。

Any assistance or clarification would be greatly appreciated. Thank you.

推荐答案

这些被称为泛型

通常,这些类型(类和接口)在定义类,接口和方法时都是参数。

In general, these enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods.

使用泛型比使用非泛型代码有很多好处,如Java教程中所示:

Using generics give many benefits over using non-generic code, as shown the following from Java's tutorial:


  • 在编译时进行更强大的类型检查。 Java编译器将强类型检查应用于通用代码,并在代码违反类型安全时发出错误。修复编译时错误比修复运行时错误更容易,这很难找到。

  • Stronger type checks at compile time. A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.

例如:

// without Generics
List list = new ArrayList();
list.add("hello");

// With Generics
List<Integer> list = new ArrayList<Integer>();
list.add("hello"); // will not compile


  • 使程序员能够实现通用算法。通过使用泛型,程序员可以实现适用于不同类型集合的通用算法,可以自定义,并且类型安全且易于阅读。

  • Enabling programmers to implement generic algorithms. By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.

    消除演员表。

    例如,以下没有泛型的代码片段需要强制转换:

    For example, the following code snippet without generics requires casting:

    List list = new ArrayList();
    list.add("hello");
    String s = (String) list.get(0);
    

    当重写为使用泛型时,代码不需要转换:

    When re-written to use generics, the code does not require casting:

    List<String> list = new ArrayList<String>();
    list.add("hello");
    String s = list.get(0); // no cast
    


  • 这篇关于&lt; E&gt;是什么? Java语法是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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