<> 在 Java 中有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11891567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:48:15  来源:igfitidea点击:

What does <> do in Java?

javalistgenericstypes

提问by GenericJam

I know if you want a list (for example) you create it like:

我知道如果你想要一个列表(例如),你可以像这样创建它:

List<String>

If you want to create a generic type of list you could do it like:

如果你想创建一个通用类型的列表,你可以这样做:

MyList<T>

So is the only thing <> does is to couple an object with a container or list? Does it have other uses? What does it actually do? Was reading on another post how putting static methods in generic types is a bad thing for type safety, so is this bad code?

那么 <> 唯一能做的就是将对象与容器或列表耦合吗?它还有其他用途吗?它实际上有什么作用?正在阅读另一篇文章如何将静态方法放在泛型类型中对类型安全来说是一件坏事,那么这是糟糕的代码吗?

public class LinkList<T> {

private final T t;
private final LinkList<T> next;

public LinkList(T t, LinkList<T> next){
    this.t = t;

    this.next = next;
}
// Creates list from array of T
public static <T> LinkList<T> getList(T[] t){
    if(t == null){
        return null;
    }
    LinkList linkList = null;
    for(int i = t.length-1; i >= 0; i--){
        linkList = new LinkList(t[i], linkList);
    }
    return linkList;
}

public T element() {
    return t;
}

public LinkList<T> getNext() {
    return next;
}

}

}

回答by kosa

<>helps compiler in verifying type safety.

<>帮助编译器验证类型安全。

Compiler makes sure that List<MyObj>holds objects of type MyObjat compile time instead of runtime.

编译器确保在编译时而不是运行时List<MyObj>保存类型的对象MyObj

Generics are mainly for the purpose of type safety at compile time. All generic information will be replaced with concrete types after compilation due to type erasure.

泛型主要用于编译时的类型安全。由于类型擦除,所有通用信息将在编译后替换为具体类型。

回答by La bla bla

When you put <>and a type inside, it is used in order to convert what would be a potential runtime exception, into a compilation error.

当你<>在里面放入一个类型时,它用于将潜在的运行时异常转换为编译错误。

Take this code for example, without generics

以这段代码为例,没有泛型

ArrayList stringList = new ArrayList();
stringList.add("string");
stringList.add(3.4);
String s = (String) stringList.get(1);

// THIS WOULD COMPILE AND PRODUCE A RUNTIME ERROR, COMPARING String TO double.

// 这会编译并产生运行时错误,将字符串比较为双倍。

If you add generics, you could could find these bugs when writing it.

如果你添加泛型,你可以在编写它时发现这些错误。

consider the following code:

考虑以下代码:

ArrayList<String> stringList = new ArrayList<String>(); // Since Java 7 you can write - new ArrayList<>()
stringList.add("string"); // OK
stringList.add(3.4); // Would not compile!

This way you can catch type-related errors in compile time.

通过这种方式,您可以在编译时捕获与类型相关的错误。

The compiler itself doesn't care whether or not you used generics. it removes all of them on compilation and acts as if you didn't used generics. however, it won't let you compile if you have a compilation error in the first place.

编译器本身并不关心您是否使用了泛型。它会在编译时删除所有这些,并且就像您没有使用泛型一样。但是,如果您首先遇到编译错误,它不会让您编译。

I also noticed I didn't answered your question about the code.

我还注意到我没有回答你关于代码的问题。

When you do something like this

当你做这样的事情时

class LinkedList<T> {
....
.... 
}

You tell the compiler that this class supports generics, and in that case it is possible to do what I've said above

你告诉编译器这个类支持泛型,在这种情况下可以做我上面说的

you could do

你可以

LinkedList<String> list = new LinkedList<String>();

Now, where ever in your class it says Tit would acts as if it says String, thus allowing only adding and mainpulating Strings.

现在,无论在您的班级中的哪个地方,它都说T它的行为就像它说的一样String,因此只允许添加和维护字符串。

回答by ameed

<>is used for a cool feature called generics.

<>用于称为泛型的很酷的功能。

Before Java 5, generics did not exist. Collections like ArrayListreturned and manipulated Objects. The problem with this is when you know that you will only store Strings, for example. But if you are working with Objectsin all your classes, not only do you have to use annoying casting (String blah = (String) list.get(9);), but if you make an error and put an Integerin your list, your program will ClassCastExceptionand burn.

在 Java 5 之前,泛型不存在。集合如ArrayList返回和操纵Objects。问题在于String,例如,当您知道您只会存储s 时。但是,如果您Objects在所有类中都使用它,不仅必须使用烦人的强制转换 ( String blah = (String) list.get(9);),而且如果您犯了错误并将其放入Integer列表中,您的程序就会ClassCastException烧毁。

Java 5 solved this with generics, so now you can say ArrayList<String>to say that you will only use Strings in this ArrayList. But what if you need to make ArrayList<Supercalifragilisticexpealidocious>? Obviously, typing that is not a pleasant experience, especially when you have to type

Java 5 用泛型解决了这个问题,所以现在你可以说ArrayList<String>你只会String在 this 中使用s ArrayList。但是如果你需要 makeArrayList<Supercalifragilisticexpealidocious>呢?显然,打字不是一种愉快的体验,尤其是当您必须打字时

ArrayList<Supercalifragilisticexpealidocious> supercaliList = new ArrayList<Supercalifragilisticexpealidocious>();

to declare one of these. Moreover, it could lead to typos, especially with a type parameter this size; at some point, you are bound to mistype a letter or two and make your program cannot find symboland burn--or worse, silently use the wrong class and cause logic errors.

声明其中之一。此外,它可能会导致拼写错误,尤其是对于这种大小的类型参数;在某些时候,您肯定会打错一两个字母,从而使您的程序cannot find symbol烧毁——或者更糟的是,默默地使用错误的类并导致逻辑错误。

Java 7 introduces the plain <>syntax. It is called the diamond operatorand makes it so you don't have to retype the type parameter (the thing inside the <>) on the right side of the assignment operator. Therefore,

Java 7 引入了简单的<>语法。它被称为菱形运算符,因此您不必<>在赋值运算符的右侧重新键入类型参数( 里面的东西)。所以,

ArrayList<Supercalifragilisticexpealidocious> supercaliList = new ArrayList<Supercalifragilisticexpealidocious>();

becomes

变成

ArrayList<Supercalifragilisticexpealidocious> supercaliList = new ArrayList<>();

which means a lot less time retyping Supercalifragilisticexpealidocious.

这意味着重新输入的时间要少得多Supercalifragilisticexpealidocious

Hope this helps!

希望这可以帮助!

回答by Code-Apprentice

<> can be used with any class you wish, not just containers. These are simply the most common since we want to be able to store any kind of Object we want in a container and still keep type safety. To understand this in more depth, you should research generics and what they are used for.

<> 可以与您希望的任何类一起使用,而不仅仅是容器。这些只是最常见的,因为我们希望能够在容器中存储我们想要的任何类型的对象,并且仍然保持类型安全。要更深入地理解这一点,您应该研究泛型及其用途。