java lt t gt 是什么意思,什么是< TYPE>在java中是什么意思

I have seen declarations, interfaces and classes that go TYPE

What does this do/mean?

解决方案

Without evidence, I believe you're talking about Java's Generics support...

Generics allow you to abstract over types

Before Java 5 it was difficult to provide classes that were capable of supporting multiple different types of Objects without having to code for each specific situation, so it was common for people to pass Object instead.

This leads to many difficult choices to make at runtime, you'd have to do a runtime check to see if it was possible to cast a given Object to a usable type...for example

List myIntList = new LinkedList(); // 1

myIntList.add(new Integer(0)); // 2

Integer x = (Integer) myIntList.iterator().next(); // 3

Now, this is reasonably obvious, but if you were passed just a List, you'd have to check each and every element in the list for correctness...

But now, we can do this...

List myIntList = new LinkedList(); // 1'

myIntList.add(new Integer(0)); // 2'

Integer x = myIntList.iterator().next(); // 3'

This is a contract that basically says "This list only contains Integer type's of objects".

With generics you can construct a single class that is capable of handling multiple different data types or a family of data types (ie constraint the parameter so that it must be extended from a particular parent type).

Iterator extends Number> itNum;

Basically says, this will contain objects that inherit from Number, include Integer, Long, Double, Float...

Often in method and class decelerations you will see something similar to...

public class MyGenericClass {...}

or

public class MyGenericClass {...}

This allows you to refer to T as if it were a concrete object type, for example...

public class MyGenericClass {

private T value;

public MyGenericClass(T value) {

this.value = value;

}

}

This allows the compiler (and JVM) to essentially "replace" the marker T with a concert type (okay, it's a little more complicated then that, but that's the magic)...

This allows to do things like...

... new MyGenericClass(new MySuperObject());

... new MyGenericClass(new MySuperSuperObject());

And know that it will only ever accept the type of object I specify...

Have a read through the link in the first paragraph, I'm sure it can do more justice then I can ;)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值