Using and Programming Generics in J2SE 5.0

NuPlayer 之 Renderer 触发postDrainAudioQueue_l()或postDrainVideoQueue()开始渲染。解码器输出数据 → NuPlayer::Decoder::onMessageReceived。音频数据存入mAudioQueue,视频数据存入mVideoQueue。• 每次写入后通过mNotifyConsumed通知解码器。• 通过AudioSink::write()写入音频设备。• 根据VSync信号和音频时钟调整渲染时机。• 通过Surface直接提交给显示系统。 阅读详情


Article
Using and Programming Generics in J2SE 5.0
  
 
By Qusay H. Mahmoud, October 2004  

In J2SE 1.4.x you can have a collection of objects where the elements may have any reference type. Some additional work, however, is still your responsibility in the sense that you are required to keep track of what types of objects your collections contain. Also, you cannot have collections of primitive data types such as ints, floats, doubles, etc. But since every data type has a corresponding reference type (for example, int has Integer), you can convert an int to an Integer before storing it in the collection. However, when an element is extracted from the collection an Object is returned that must be cast to an Integer in order to ensure type safety. All this makes Java programs unnecessarily hard to read and maintain, and are more likely to fail with runtime errors.

If a collection contains information about the element type, there would be no need to keep track of what collections you have and also there would be no need for casting. This would make programs easier to read and maintain, and less likely to fail at runtime. J2SE 5.0 has added a new core language feature known as generics (also known as parameterized types), that provides compile-time type safety for collections and eliminate the drudgery of casting. The effort of adding generics to Java is led by Sun Microsystems as JSR 14 under the Java Community Process (JCP).

Generics are one of the most frequently requested language extensions to Java, and they have been finally added in J2SE 5.0. This article provides an introduction to programming with generics.

The Need for Generics

The motivation for adding generics to the Java programming language stems from the fact that a collection doesn't contain information about the element type, the need to keep track of what type of elements collections contain, and the need for casts all over the place. Using generics, a collection is no longer treated as a list of Object references, but you would be able to differentiate between a collection of references to Integers and collection of references to Bytes. A collection with a generic type has a type parameter that specifies the element type to be stored in the collection.

As an example, consider the following segment of code that creates a linked list and adds an element to the list:

LinkedList list = new LinkedList();
list.add(new Integer(1));
Integer num = (Integer) list.get(0);

As you can see, when an element is extracted from the list it must be cast. The casting is safe as it will be checked at runtime, but if you cast to a type that is different from, and not a supertype of, the extracted type then a runtime exception, ClassCastException will be thrown.

Using generic types, the previous segment of code can be written as follows:

LinkedList<Integer> list = new LinkedList<Integer>();
list.add(new Integer(1));
Integer num = list.get(0);

Here we say that LinkedList is a generic class that takes a type parameter, Integer in this case.

As you can see, you no longer need to cast to an Integer since the get() method would return a reference to an object of a specific type (Integer in this case). If you were to assign an extracted element to a different type, the error would be at compile-time instead of run-time. This early static checking increases the type safety of the Java language.

To reduce the clutter, the above example can be rewritten as follows...using autoboxing:

LinkedList<Integer> list = new LinkedList<Integer>();
list.add(1);
int num = list.get(0);

As a complete example, consider the following class, Ex1, which creates a collection of two Strings and one Integer, and then prints out the collection:

Ex1.java

import java.util.*;

public class Ex1 {

  private void testCollection() {
    List list = new ArrayList();
    list.add(new String("Hello world!"));
    list.add(new String("Good bye!"));
    list.add(new Integer(95));
    printCollection(list);
  }

  private void printCollection(Collection c) {
    Iterator i = c.iterator();
    while(i.hasNext()) {
      String item = (String) i.next();
      System.out.println("Item: "+item);
    }
  }

  public static void main(String argv[]) {
    Ex1 e = new Ex1();
    e.testCollection();
  }
}

Again, an explicit cast is required in the printCollection method. This class compiles fine, but throws a CLassCastException at runtime as it attempts to cast an Integer to a String:

Item: Hello world!
Item: Good bye!
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer
        at Ex1.printCollection(Ex1.java:16)
        at Ex1.testCollection(Ex1.java:10)
        at Ex1.main(Ex1.java:23)

Using Generics

Using generics, the Ex1 class above can be written as follows:

Ex2.java

import java.util.*;

public class Ex2 {

  private void testCollection() {
    List<String> list = new ArrayList<String>();
    list.add(new String("Hello world!"));
    list.add(new String("Good bye!"));
    list.add(new Integer(95));
    printCollection(list);
  }

  private void printCollection(Collection c) {
    Iterator<String> i = c.iterator();
    while(i.hasNext()) {
      System.out.println("Item: "+i.next());
    }
  }

  public static void main(String argv[]) {
    Ex2 e = new Ex2();
    e.testCollection();
  }
}

Now, if you try to compile this code, a compile-time error will be produced informing you that you cannot add an Integer to a collection of Strings. Therefore, generics enable more compile-time type checking and therefore mismatch errors are caught at compile-time rather than at run-time.

You may have already noticed the new syntax used to create an instance of ArrayList (List<String> list = new ArrayList<String>()). ArrayList is now a parameterized type. A parameterized type consists of a class or interface name E and a parameter section <T1, T2, ..., Tn>, which must match the number of declared parameters of E, and each actual parameter must be a subtype of the formal parameter's bound types. The following segment of code shows parts of the new class definition for ArrayList:

public class ArrayList<E> extends AbstractList<E> implements List<E>, 
    RandomAccess, Cloneable, Serializable {
   // ...
}

Here E is a type variable, which is an unqualified identifier. It simply acts as a placeholder for a type to be defined when the list is used.

Implementing Generic Types

In addition to using generic types, you can implement your own. A generic type has one or more type parameters. Here is an example with only one type parameter called E. A parameterized type must be a reference type, and therefore primitive types are not allowed to be parameterized types.

interface List<E> {
   void add(E x);
   Iterator<E> iterator();
}

interface Iterator<E> {
   E next();
   boolean hasNext();
}


class LinkedList<E> implements List<E> {
   // implementation   
}

Here, E represents the type of elements contained in the collection. Think of E as a placeholder that will be replaced by a concrete type. For example, if you write LinkedList<String> then E will be replaced by String.

In some of your code you may need to invoke methods of the element type, such as Object's hashCode() and equals(). Here is an example that takes two type parameters:

class HashMap<K, V> extends AbstractMap<K, V> implements Map<K, V> {

   // ...

   public V get(Object k) {
      ...
      int hash = k.hashCode();  
      ...
   }
   // ...   
}

The important thing to note is that you are required to replace the type variables K and V by concrete types that are subtypes of Object.

Generic Methods

Genericity is not limited to classes and interfaces, you can define generic methods. Static methods, nonstatic methods, and constructors can all be parameterized in almost the same way as for classes and interfaces, but the syntax is a bit different. Generic methods are also invoked in the same way as non-generic methods.

Before we see an example of a generics method, consider the following segment of code that prints out all the elements in a collection:

public void printCollection(Collection c) {
   Iterator i = c.iterator();
   for(int k = 0;k<c.size();k++) {
     System.out.printn(i.next());
   }
}

Using generics, this can be re-written as follows. Note that the Collection<?> is the collection of an unknown type.

void printCollection(Collection<?> c) {
   for(Object o:c) {
      System.out.println(e);
   }
}

This example uses a feature of generics known as wildcards.

Wildcards

There are three types of wildcards:

  1. "? extends Type": Denotes a family of subtypes of type Type. This is the most useful wildcard
  2. "? super Type": Denotes a family of supertypes of type Type
  3. "?": Denotes the set of all types or any

As an example of using wildcards, consider a draw() method that should be capable of drawing any shape such as circle, rectangle, and triangle. The implementation may look something like this. Here Shape is an abstract class with three subclasses: Circle, Rectangle, and Triangle.

public void draw(List<Shape> shape) {
  for(Shape s: shape) {
    s.draw(this);
  }
}

It is worth noting that the draw() method can only be called on lists of Shape and cannot be called on a list of Circle, Rectangle, and Triangle for example. In order to have the method accept any kind of shape, it should be written as follows:

public void draw(List<? extends Shape> shape) {
   // rest of the code is the same
}

Here is another example of a generics method that uses wildcards to sort a list into ascending order. Basically, all elements in the list must implement the Comparable interface.

public static <T extends Comparable<? super T>> void sort(List<T> list) {
   Object a[] = list.toArray();
   Arrays.sort(a);
   ListIterator<T> i = list.listIterator();
   for(int j=0; j<a.length; j++) {
      i.index();
      i.set((t)a[j]);
   }
}

Changes to the Java Specification, JVM, and APIs

In order to support generic types, some modifications are necessary to the Java programming language, the Java virtual machine1, and the Java APIs. The notable changes to the Java APIs are related to the Collection hierarchy in the java.util package, changes to the java.lang.Class class, and the java.lang.reflect package so that it is possible to examine a type, method, constructor or field declaration and obtain generic type information. If you like to learn about the exact changes, please see JSR 14: Adding Generics to the Java Programming Language.

Behind the Scenes

Generics are implemented by the Java compiler as a front-end conversion called erasure, which is the process of translating or rewriting code that uses generics into non-generic code (that is, maps the new syntax to the current JVM specification). In other words, this conversion erases all generic type information; all information between angle brackets is erased. For example, LinkedList<Integer> will become LinkedList. Uses of other type variables are replaced by the upper bound of the type variable (for example, Object), and when the resulting code is not type correct, a cast to the appropriate type is inserted.

Java Generics vs. C++ Templates

While generics look like the C++ templates, it is important to note that they are not the same. Generics simply provide compile-time type safety and eliminate the need for casts. The main difference is encapsulation: errors are flagged where they occur and not later at some use site, and source code is not exposed to clients. Generics use a technique known as type erasure as described above, and the compiler keeps track of the generics internally, and all instances use the same class file at compile/run time.

A C++ template on the other hand is just a fancy macro processor; whenever a template class is instantiated with a new class, the entire code for the class is reproduced and recompiled for the new class.

Conclusion

Generics are a new core feature in J2SE 5.0, and a major addition to the core language. This feature provides a useful abstract and compile-time type safety for collections and eliminates the drudgery of casting. This article provided an overview and introduction to Java generics, and showed how to use generics as well as write your own. The examples provided in this article demonstrate how useful this new core feature is.

For More Information

- Download J2SE 5.0
- GJ: Extending the Java programming language with type parameters
- JSR 14: Adding Generics to the Java Programming Language
- Generics Tutorial (Generics in the Java Programming Language)

Acknowledgments

Thanks to Gilad Bracha for commenting on earlier drafts, and for providing some of the examples used in this article.


copyright © Sun Microsystems, Inc 
 










ZYNQ系列PS侧和PL侧DDR3或DDR4在AD(Altium Designer 25)中的layout布线规则约束 DDR3或DDR4的PCB布线规则通常有相对固定的要求,对应的,在PCB设计时有固定的约束设置。 阅读详情

相关推荐

扫地机器人解决方案:工作原理与硬件构成

房间里柜子,鞋子,床,座椅,人都在什么地方?3、数字信号处理器。这主要是为控制芯片进行路径规划后,下发指令给执行的电机,包括舵轮(扫地机人前进,转向的轮子),扫地刷的电机,吸尘器的电机,让这些电机工作。扫地机器人的大脑主要用来规划路径,避障,以及人机交互,例如:人类设定打扫范围,以及语音指导扫地机器人进行打扫,都需要处理器进行处理后,将指令下发到执行机构。小脑属于跟执行层最近的控制区域,例如我们上面说的,后面两个处理器:数字信号处理器和微控制器都是对执行层(电机),进行控制和回馈外部信息的处理器。

迷途 7422

JAVA泛型编程全面总结

JAVA泛型编程总结                                                                                                                                                                ——by书生 1介绍 Java泛型编程是JDK1.5版

__七把刀__ 3818

【高清照片】深圳光博会看PCIe Over Fibre 实现方案

本文分析了PCIe over Fibre技术及其在数据中心的应用前景。该技术通过光纤延伸PCIe总线,解决了传统铜缆距离限制问题,支持跨机架资源池化。目前主要有两种实现方式:CDFP混合光缆方案和Retimer转接卡方案,各有优缺点。文章还探讨了CDFP接口的现状、低速信号传输解决方案,以及PCIe速率与光通信发展的对应关系。最后对比了PCIe光缆与以太网光缆的关键差异,指出PCIe光互连在协议透明度和边带信号处理上的特殊要求。随着标准推进,PCIe over Fibre将成为数据中心扩展高带宽、低时延互连

Saniffer的博客 1395

Java 泛型详解

介绍 JDK 5.0 引入的语言特性 通常在容器或容器的子接口中使用 编译器在编译时可以检查程序的类型正确性 为什么需要泛型 在编译时进行更强的类型检查 Java 编译器对泛型代码应用强类型检查,并在代码违反类型安全时发出错误。 修复编译时错误比修复运行时错误更容易,后者很难发现。 消除类型转换 实现通用算法 通过使用泛型,程序员可以实现适用于不同类型集合的泛型算法,并且类型安全且易于阅读。 泛型与泛型子类型 泛型类型声明并不会因为泛型的不同而存在多个副本,泛型类型声明只会编译一次,并编译成

Wzeefeng的博客 323

别再纠结VS还是VSCode了!新手C#环境搭建保姆级指南(含.NET Core安装验证)

本文为C#新手提供Visual Studio与VS Code的深度对比及环境搭建指南,涵盖.NET Core安装验证、工具选择决策框架及实战配置技巧。帮助开发者根据项目需求选择合适工具,快速搭建高效开发环境,提升编码效率。

weixin_30455023的博客 562

知识图谱_知识图谱 | 知识图谱做用户画像

导读:最近一直在思考怎么用知识图谱做推荐,但是目前能知道的内容都是基于路径的推荐和基于图特征的推荐,所以能不能换一个角度,探究一下用知识图谱怎么做用户画像,因为画像也是推荐系统重要的一部分。现在的知识图谱+推荐怎么做的传统的用户画像怎么做现在的知识图谱+推荐怎么做的?基于路径:可以理解成基于图谱的多路径召回,或者多路径推荐,然后根据路径的转移概率进行排序从而达到推荐的效果,基于路径比较适合简单的推...

weixin_28801659的博客 1466

第13章_泛型(Generic)

JAVA 2023 学习笔记 原视频为B站尚硅谷Java零基础全套视频教程(宋红康2023版,java入门自学必备) https://www.bilibili.com/video/BV1PY411e7J6

JOKER的博客 259

完美解决LBP2900打印机安装驱动提示无法识别USB及连接错误等问题(附Win11全新安装支持及卸载方案)

LBP2900打印机虽然经典老旧,但在Win11上依然可以完美使用!许多网上教程都无视安装失败后的问题,在此分享一种全新、100%有效的方法来解决驱动连接错误和无法识别USB设备的问题。无论是新安装还是卸载重装,这个方法都适用。本文整合了通用驱动包,支持Win2000到Win11系统,操作简单,轻松摆脱安装困扰,享受无忧打印体验!

心开始の未来~的博客 2万+

[译] 4.通配符

<<泛型和子类型·目录·泛型方法>> 通配符 (Wildcards) 考虑一个问题...

chijie6848的博客 213

educoder中Hive综合应用案例 — 用户搜索日志分析

Hive综合应用案例 — 用户搜索日志分析

weixin_46026136的博客 4807

Python爬虫教程:微博热点话题抓取与社交媒体分析

微博是中国最大的社交媒体平台之一,拥有海量的用户和丰富的讨论话题。通过爬取微博的热门话题和讨论内容,我们可以深入分析用户的兴趣、舆论走势、社会情绪等。通过爬取微博的热点话题和讨论内容,我们可以获得关于当前热门话题的宝贵数据,并基于这些数据进行多种社交媒体分析。本文将通过Python爬虫技术,详细介绍如何抓取微博上的热门话题、话题讨论内容,并进行社交媒体分析。希望本文为你提供了一个全面的微博数据抓取与分析的指南,帮助你在社交媒体数据分析的道路上迈出坚实的第一步。微博上的一些页面内容是静态的,可以直接通过。

2201_76125261的博客 594

Java(老白再次入门) - 泛型

本系列文章均为尚硅谷资源!如有侵权,我将立即删除! Java基础知识图解 1.为什么要有泛型 泛型的设计背景 集合容器类在设计阶段/声明阶段不能确定这个容器到底实际存的是什么类型的对象,所以在JDK1.5之前只能把元素类型设计为Object,JDK1.5之后使用泛型来解决。 因为这个时候除了元素的类型不确定,其他的部分是确定的,例如关于这个元素如何保存,如何管理等是确定的,因此此时把元素的类型设计成一个参数,这个类型参数叫做泛型。Collection,List,ArrayList 这个就是类型参数.

Syntactic Sugar 341

聊聊5G RedCap与eRedCap

而eRedCap作为R18引入的升级版本,进一步将峰值速率限制为10Mbps,仅支持FR1频段,通过减少物理资源块(PRB)数量和优化休眠机制,实现了更低的功耗和成本,成为NB-IoT/LTE-M的理想升级路径。RedCap与eRedCap的出现,正是为了填补“中间地带”—它们既具备高于mMTC的传输速率(接近LTE Cat 4水平),又能实现传统5G NR无法企及的低功耗与低成本,完美适配智能电表、工业网关、智能穿戴设备等“中等需求”物联网设备。时延则低至50ms以下,满足工业机械远程控制的实时性需求。

asd199086的博客 1752

J2SE 5.0 新特性

The Tiger feature list is defined in JSR-176 (J2SE 5.0 (Tiger) Release Content), which serves as an umbrella JSR that only lists APIs defined in other component JSRs. Please see JSR-176 for details ab

设计模式空间 1313

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

Java各版本语法增强特性

Java SE 8增强特性 ·        Lambda 表达式可以封装一个简单的行为并把它传递到其他代码. 你可以使lambda表达式用特定的行为处理集合中的每一个元素. Lambda下面的特性使用了lambda表达式: o   方法引用 是简洁的,可读性更高的lambda表达式。它用于引用已存在的方法. o   默认方法 可以为接口添加一个新的功能,并且兼容较老的版本的接口. 他们是已

fengwind1的专栏 1457

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

JDK5.0新特性

“JDK1.5”(开发代号猛虎)的一个重要主题就是通过新增一些特性来简化开发,这些特性包括泛型,for-each 循环,自动装包/拆包,枚举,可变参数, 静态导入 。使用这些特性有助于我们编写更加清晰,精悍,安全的代码。下面我们简单介绍一下这些新特性。1.泛型(Generic)C++通过模板技术可以指定集合的元素类型,而Java在1.5之前一直没有相对应的功能。一个集合可以放任何类型的对象,相

gzkaminlee的专栏 1012

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

Java基础学习——泛型(generics)二

本文主要是介绍了Java泛型里的通配符类型(wildcard type),受限通配符(Bounded Wildcards),以及泛型函数的使用场景。

双湖之梦的专栏 1693

jdk 1.5新特性说明

“JDK1.5”的一个重要主题就是通过新增一些特性来简化开发,这些特性包括泛型,for-each 循环,自动装包/拆包,枚举,可变参数, 静态导入 。使用这些特性有助于我们编写更加清晰,精悍,安全的代码。 一. 首先简单介绍一下各种特性及其使用 1.泛型(Generic)C++通过模板技术可以指定集合的元素类型,而Java在1.5之前一直没有相对应的功能。一个集合可以放任何类型的对象,相应地从集合...

笨得很想飞的专栏 228

Java——通配符

考虑编写打印出集合中所有元素的例程的问题。以下是您可以在旧版本的语言中编写它(即5.0之前的版本): void printCollection(Collection c){ Iterator i = c.iterator(); for(k = 0; k &lt;c.size(); k ++){ 的System.out.println(i.next()); ...

专注Java(全栈)应用开发,求知若渴,虚心若愚,talk is cheap, show me the code. 1067

Java之JDK 1.5新特性

---------------------- ASP.Net+Android+IOS开发、.Net培训、期待与您交流! ---------------------- 下面简略的说说jdk1.5的新特性。 泛型(Generics)--为集合(collections)提供编译时类型安全,无需每刻从Collections取得一个对象就进行强制转换(cast) 增强的“for”循环(Enha

jy_aicn的专栏 810

scala 泛型基础之jdk1.5引入的泛型 generics (一)

1.            介绍 JDK1.5中引入了对java语言的多种扩展,泛型(即其中之一。 Generics允许对类型进行抽象(abstract over types)。最常见的例子是集合类型(Container types),Collection的类树中任意一个即是。 下面是那种典型用法:        List myIntList = new LinkedList();

shadowsama的博客 468

Collections 常用方法

此类完全由在 collection 上进行操作或返回 collection 的静态方法组成。它包含在 collection上操作的多态算法,即“包装器”,包装器返回由指定 collection 支持的新 collection,以及少数其他内容 如果为此类的方法所提供的 collection 或类对象为 null,则这些方法都将抛出NullPointerException。 首先定义一个工具类:

public 1265

011Java泛型

泛型的设计背景: 集合容器类在设计阶段/声明阶段不能确定这个容器到底实际存的是什么类型的对象,所以在JDK1.5之前只能把元素类型设计为Object,JDK1.5之后使用泛型来解决。因为这个时候除了元素的类型不确定,其他的部分是确定的,例如关于这个元素如何保存,如何管理等是确定的,因此此时把元素的类型设计成一个参数,这个类型参数叫做泛型。例如:Collection,List,ArrayList这个就是类型参数,即泛型。 泛型的概念: 所谓泛型,就是允许在定义类、接口时通过一个标识表示类中某个属性的类型

传说中国的博客 409

Flink-Tuple

怀念二抱三抱

文天大人 902

Generics in C#

IntroductionSome New features have been added to C# language with version 2.0 of .NET. which are: Generics Iterators Anonymous methods Partial classes In this Article I will explain abou

流男@水孩 1068

flink任务常见报错及解决办法

1、flink任务无法从checkpoint启动 场景一、flink任务运行过程中出现异常时(如checkpoint失败次数超过配置阈值),自动重启出现算子异常,无法恢复正常运行。 场景二、手动下线任务,选择上一次的checkpoint启动时,出现算子异常,无法启动。 报错如下: java.lang.Exception: Exception while creating StreamOperatorStateContext. at org.apache.flink.streaming.api.

yiweiyi329的博客 4万+
上一篇: 妈的,这个鸟网速!!!
下一篇: Winter Fun Pack 2004 for Windows XP
naxin
博客等级 码龄25年 31粉丝 329原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值