generics.pptVIP

  • 4
  • 0
  • 约8.55千字
  • 约 32页
  • 2016-03-30 发布于江苏
  • 举报
学习动物精神 12、善解人意的海豚:常常问自己:我是主管该怎么办才能有助于更好的处理事情的方法。在工作上善解人意, 会减轻主管、共 事者的负担,也 让你更具人缘。 * * Intro to Generics Based on materials from HF, CC and CJ2. Contents Java Generics Most used features of generics Generic classes Variables of generic types Methods that take generic types Bounded type parameters Arrays vs. Generics Wildcards Java collections ≤ v1.4 The initial Java collections stored values of type Object. They could store any type, since all types are subclasses of Object. But you had to cast the results, which was tedious and error-prone. Examining the elements of a collection was not type-safe. // in Java 1.4: ArrayList names = new ArrayList(); names.add(Marty Stepp); names.add(Stuart Reges); String teacher = (String) names.get(0); // this will compile but crash at runtime; bad Point oops = (Point) names.get(1); Java Generics Type Parameters (Generics) Since Java 1.5, when constructing a java.util.ArrayList, we specify the type of elements it will contain between and . We say that the ArrayList class accepts a type parameter, or that it is a generic class. Use of the raw type ArrayList without leads to warnings. ListString names = new ArrayListString(); names.add(Marty Stepp); names.add(Stuart Reges); String teacher = names.get(0); // no cast Point oops = (Point) names.get(1); // error Java Generics ListType name = new ArrayListType(); Parametric polymorphism parametric polymorphism (参量多态): Ability for a function or type to be written in such a way that it handles values identically without depending on knowledge of their types. Such a function or type is called a generic function or data type. first introduced in ML language in 1976 now part of many other languages (Haskell, Java, C#, Delphi) C++ templates are similar but lack various features/flexibility Motivation: Parametric polymorphism allows you to write flexible, general code without sacrificing type safety. Most commonly used in Java with collections. Also used in reflection. Jav

文档评论(0)

1亿VIP精品文档

相关文档