什么是<>在Java中做? [英] What does <> do in Java?

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

问题描述

我知道你是否想要一个列表(例如)创建它:

  List< String> 

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

  MyList< T> 

所以<>所做的只是将一个对象与一个容器或列表连接起来?它有其他用途吗?它实际上做了什么?
在另一篇文章上看到如何将静态方法放在泛型中对于类型安全来说是一件坏事,那么这个错误的代码是如何?

  public class LinkList< T> {

private final T t;
private final LinkList< T>下一个;

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

this.next = next;
}
//创建T $ b $数组中的列表public static< T>链表< 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(){
next next;
}

}

解决方案

<> 帮助编译器验证类型安全性。在编译时而不是运行时确保 List< MyObj> 包含 MyObj 类型的对象。 b
$ b

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


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;
}

}

解决方案

<> helps compiler in verifying type safety.

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

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.

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

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