精华内容
下载资源
问答
  • Generics

    2020-03-20 21:38:51
    Generics JDK 5.0 introduces several new extensions to the Java programming language. One of these is the introduction of generics. This trail is an introduction to generics. You may be familiar wi...

    Generics

    • JDK 5.0 introduces several new extensions to the Java programming language. One of these is the introduction of generics.

    • This trail is an introduction to generics. You may be familiar with similar constructs from other languages, most notably C++ templates. If so, you’ll see that there are both similarities and important differences. If you are unfamiliar with look-a-alike constructs from elsewhere, all the better; you can start fresh, without having to unlearn any misconceptions.

    • Generics allow you to abstract over types. The most common examples are container types, such as those in the Collections hierarchy.

    Here is a typical usage of that sort:
    
    List myIntList = new LinkedList(); // 1
    myIntList.add(new Integer(0)); // 2
    Integer x = (Integer) myIntList.iterator().next(); // 3        
    The cast on line 3 is slightly annoying. Typically, the programmer knows what kind of data has been placed into a particular list. However, the cast is essential. The compiler can only guarantee that an Object will be returned by the iterator. To ensure the assignment to a variable of type Integer is type safe, the cast is required.
    
    Of course, the cast not only introduces clutter. It also introduces the possibility of a run time error, since the programmer may be mistaken.
    
    What if programmers could actually express their intent, and mark a list as being restricted to contain a particular data type? This is the core idea behind generics. Here is a version of the program fragment given above using generics:
    
    List<Integer> 
        myIntList = new LinkedList<Integer>(); // 1'
    myIntList.add(new Integer(0)); // 2'
    Integer x = myIntList.iterator().next(); // 3'
    Notice the type declaration for the variable myIntList. It specifies that this is not just an arbitrary List, but a List of Integer, written List<Integer>. We say that List is a generic interface that takes a type parameter--in this case, Integer. We also specify a type parameter when creating the list object.
    
    Note, too, that the cast on line 3' is gone.
    

    Now, you might think that all we’ve accomplished is to move the clutter around. Instead of a cast to Integer on line 3, we have Integer as a type parameter on line 1’. However, there is a very big difference here. The compiler can now check the type correctness of the program at compile-time. When we say that myIntList is declared with type List, this tells us something about the variable myIntList, which holds true wherever and whenever it is used, and the compiler will guarantee it. In contrast, the cast tells us something the programmer thinks is true at a single point in the code.

    The net effect, especially in large programs, is improved readability and robustness.

    展开全文
  • GENERICS

    2011-12-12 20:52:44
     //7.1: try this--it shows if no generics here, any type can be added to this list  //and it won't be forced to cast to Fruit, because it really didn't erase type  List list77 = new ArrayList()...
      
    

    package genericAndCollection;

    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;

    public class TestGenerics {
     
     static class Fruit{}
     
     static class Apple extends Fruit{}
     
     static class Orange extends Fruit{}
     
     public static void main(String[] args) {
      //1: the difference between ? and T
      //?: means that any number of non-determined class type, it represents N
      //T: means that one non-determined class type, it represents one
      
      //2: generics are not implementing polymorphism 
      List<Fruit> list = new ArrayList<Apple>();
      
      //3:static type or apparent type can not write while using the extends
      //to determine the type edge (downwards)
      List<? extends Fruit> list1 = new ArrayList<Apple>();
      list1.add(null);//otherwise will get compilation error
      //3.1: correct way
      List<Apple> list111 = new ArrayList<Apple>();
      list111.add(new Apple());
      List<? extends Fruit> list11 = list111;
      for(Fruit f: list11){}//to do}--read only
      
      //4: static type or apparent type can not read while using the super
      // to determine the type edge (upwards)
      //here, Gabriel said we can not get(compilation error) is wrong, it can not
      //use get due to no element there
      List<? super Fruit> list2 = new ArrayList<Fruit>();
      list2.get(0);
      //4.1: correct way
      List<Fruit> list22 = new ArrayList<Fruit>();
      list22.add(new Fruit());
      List<? super Fruit> list222 = list22;
      list222.get(0);
      
      //5: the actual type can not use ?, because jvm will have to know which
      //actual type initiated, here ? extends Fruit is any number of type possible
      //edge to Fruit
      List<? extends Fruit> list3 = new ArrayList<? extends Fruit>();
      
      //6: Array with generics, it has been implemented Polymorphism
      Fruit[] fruit = new Apple[5];
      fruit[0] = new Apple();//no error here, because while it runs, javap shows
              //anewarray command in bytecode, it doesn't actually init
                             //the instance of Fruit and Apple, it uses type [Fruit
      
      //7: force to cast while traverse using iterator
      List<Fruit> list7 = new ArrayList<Fruit>();
      //it records the actual types to meta data which located in signature
      //if in method parameter
      list7.add(new Apple());
      list7.add(new Orange());
      Iterator it = list7.iterator();
      while(it.hasNext()){
       System.out.println(it.next());
      }
      //7.1: try this--it shows if no generics here, any type can be added to this list
      //and it won't be forced to cast to Fruit, because it really didn't erase type
      List list77 = new ArrayList();
      list77.add(new Object());
      list77.add(new Orange());
      Iterator it1 = list77.iterator();
      while(it1.hasNext()){
       System.out.println((Apple)it1.next());//please do not froce it to cast
                  //will have java.lang.ClassCastException
      }
     }
    }

    展开全文
  • Generics-源码

    2021-03-29 13:51:13
    Generics
  • Java - Generics are not real generics

    万次阅读 2019-10-15 15:36:47
    分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!...Java 5 added generics into the language. This allowed programmers to specify class types as parameters to other classes and m...

    分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net

    Java 5 added generics into the language. This allowed programmers to specify class types as parameters to other classes and maintain type safety. For instance Set<Integer> is a set of integers and if you try to add a non-integer to it, a compile time error should occur.

    Java had been around a while by the time generics were added. Unfortunately it was considered too hard to add generics to the Java bytecode that forms a running Java program. Instead generics are just syntactic sugar. When a Java program is compiled the generics are checked, but after that they are stripped out. The bytecode that is run does not know anything about generics. This means it is possible to violate the generics constraints in the code at run-time (because the constraints don’t exist at run-time).

    Below is an example demonstrating the problem. A set of integers is created, but then using reflection a string is added to the set. This is clearly a violation of the set’s definition. However, reflection is a run-time process and the compiler is not smart enough to detect the potential error at compile-time (which would be very hard to do). If the set is now inspected (and not checked carefully), it will look like the integer 1 is in the set, rather than the actual string “1”. At this point various errors can occur, from the subtle contains error below, to outright ClassCastException if elements are extracted from the set as integers. As an aside, reflection is very cool and a great tool, but from my experience, most of the time it is the wrong tool.

    Set<Integer> integerSet = new HashSet<Integer>();
    Method addMethod = integerSet.getClass().getMethod("add", Object.class);
    addMethod.invoke(integerSet, "1");
    integerSet.contains(1); // -> false

    Remember, Java generics are not real generics. In particular pay special attention to using reflection on generic objects.

    展开全文
  • Const generics

    2021-01-08 20:37:23
    <div><p>This is a new const generics RFC which addresses the issues around equality between const variables that were raised in <a href="https://internals.rust-lang.org/t/lang-team-minutes-const-...
  • java-generics-源码

    2021-03-27 22:13:26
    java-generics
  • Generics.java-源码

    2021-03-10 13:40:50
    Generics.java
  • TS_Generics-源码

    2021-03-09 02:19:18
    TS_Generics
  • generics C#

    2008-04-13 11:27:08
    c# generics DEMO
  • Java Generics Cheatsheet

    2018-06-19 19:34:49
    Java Generics Cheatsheet, your convenient way to check and learn!
  • JDK 1.5之Generics

    2021-01-20 14:20:46
    Generics 是JDK 1.5 一个最重要的特性,主要用来处理Collection。 以下代码在JDK 1.5 调试通过。 代码实例1: Demo.java package maoxiang.examples.jdk15.generics; import java.util.ArrayList; import java.util....
  • Generics in Java, Java generics 的使用 1 Introduction to generics Generics are a way to tell a compiler what type of object a collection can contain. The idea is to allow type (Integer, String, … etc...

    Generics in Java, Java generics 的使用

    1 Introduction to generics

    Generics are a way to tell a compiler what type of object a collection can contain. The idea is to allow type (Integer, String, … etc and user defined types) to be a parameter to methods, classes and interfaces. For example, classes like HashSet, ArrayList, HashMap, etc use generics very well.

    Advantages of Generics:

    Programs that uses Generics has got many benefits over non-generic code.

    • Code Reuse 代码复用: We can write a method/class/interface once and use for any type we want.

    • Type Safety 类型安全 : Generics make errors to appear compile time than at run time (It’s always better to know problems in your code at compile time rather than making your code fail at run time). Suppose you want to create an ArrayList that store name of students and if by mistake programmer adds an integer object instead of string, compiler allows it. But, when we retrieve this data from ArrayList, it causes problems at runtime.

    // A Simple Java program to demonstrate that NOT using 
    // generics can cause run time exceptions 
    import java.util.*; 
      
    class Test 
    { 
        public static void main(String[] args) 
        { 
            // Creatinga an ArrayList without any type specified 
            ArrayList al = new ArrayList(); 
      
            al.add("Sachin"); 
            al.add("Rahul"); 
            al.add(10); // Compiler allows this 
      
            String s1 = (String)al.get(0); 
            String s2 = (String)al.get(1); 
      
            // Causes Runtime Exception 
            String s3 = (String)al.get(2); 
        } 
    } 
    
    // Using generics converts run time exceptions into  
    // compile time exception. 
    import java.util.*; 
      
    class Test 
    { 
        public static void main(String[] args) 
        { 
            // Creating a an ArrayList with String specified 
            ArrayList <String> al = new ArrayList<String> (); 
      
            al.add("Sachin"); 
            al.add("Rahul"); 
      
            // Now Compiler doesn't allow this 
            al.add(10);  
      
            String s1 = (String)al.get(0); 
            String s2 = (String)al.get(1); 
            String s3 = (String)al.get(2); 
        } 
    } 
    
    • Individual Type Casting is not needed : If we do not use generics, then, in the above example every-time we retrieve data from ArrayList, we have to typecast it. (即String s1 = (String)al.get(0); ) Typecasting at every retrieval operation is a big headache. If we already know that our list only holds string data then we need not to typecast it every time.
    // We don't need to typecast individual members of ArrayList 
    import java.util.*; 
    
    class Test 
    { 
    	public static void main(String[] args) 
    	{ 
    		// Creating a an ArrayList with String specified 
    		ArrayList <String> al = new ArrayList<String> (); 
    
    		al.add("Sachin"); 
    		al.add("Rahul"); 
    
    		// Typecasting is not needed 
    		String s1 = al.get(0); 
    		String s2 = al.get(1); 
    	} 
    } 
    
    
    • Implementing generic algorithms: By using generics, we can implement algorithms that work on different types of objects and at the same they are type safe too.

    2 Generic methods in Java

    Generic methods in Java are methods that allow you to create a new type parameter just for that method. This is useful if you are writing a method but want to be flexible about the type of objects you can pass in.

    I have an array of characters called charArray. I also have an array of booleans called boolArray, and an array of integers called intArray. Then, I have created a method called arrayToList that iterates through all of the objects in an array and adds them to a list. I want to be able to pass any of these arrays into the method, even though they are of different types. So the first thing I have tried is making the arguments of the array to list method object types.

    public class GenericMethods {
    
        static Character[] charArray = {'h', 'e', 'l', 'l', 'o'};
        static Integer[] intArray = {1, 2, 3, 4, 5};
        static Boolean[] boolArray = {true, false, true};
    
        public static List arrayToList(Object[] array, List<Object> list) {
            for (Object object : array) {
                list.add(object);
            }
            return list;
        }
    
        public static void main(String[] args) {
            List<Character> charList = arrayToList(charArray, new ArrayList<>());
            List<Boolean> boolList = arrayToList(boolArray, new ArrayList<>());
            List<Integer> intList = arrayToList(intArray, new ArrayList<>());
        }
    }
    

    Using objects means that I lose type safety. For example, in the main method, if I change the type of intList to string and compile this file, I don’t get any errors.

    The solution is to make the array to list method a generic method The first thing I need to do is create a new type variable, which I will call T. This type variable only has local scope.

    public class GenericMethods {
    
        static Character[] charArray = {'h', 'e', 'l', 'l', 'o'};
        static Integer[] intArray = {1, 2, 3, 4, 5};
        static Boolean[] boolArray = {true, false, true};
    
        public static <T> List<T> arrayToList(T[] array, List<T> list) {
            for (T object : array) {
                list.add(object);
            }
            return list;
        }
    
        public static void main(String[] args) {
            List<Character> charList = arrayToList(charArray, new ArrayList<>());
            List<Boolean> boolList = arrayToList(boolArray, new ArrayList<>());
            List<Integer> intList = arrayToList(intArray, new ArrayList<>());
            System.out.println(intList.get(0));
        }
    }
    

    Using this approach, I can keep the method flexible, but I can discover errors in the code much earlier on.

    3 Using vargs in Java

    Sometimes you might want to write a method that takes a variable number of arguments. In Java there is a feature called variable-length arguments, or varargs for short, which allows you to do this.

    在写printShoppingList() method 的时候,不用让输入必须是列表,比如 printShoppingList(String[] items) , Instead,我们可以用三个点代替 [ ], 这样这个method接受多个variable输入,自动成为一个list.

    public class Varargs {
        
        public static void main(String[] args) {
            String imem1 = "Apples";        
            String item2 = "Oranges";
            String item3 = "Pears";
            printShoppingList(imem1, item2, item3);
            printShoppingList("Bread", "Milk", "Eggs", "Bananas");
        }
        
        private static void printShoppingList(String... items) {
            System.out.println("SHOPPING LIST");
            for (int i = 0; i < items.length; i++) {
                System.out.println(i + 1 + ": " + items[i]);
            }
            System.out.println();
    
        }
    }
    

    Using a vararg method has made my code shorter and simpler, but it is still easy to read and understand.

    4 The substitution principle in Java

    he substitution principle, which is also known as the Liskov Substitution Principle, is an important concept in object-oriented programming because it allows you to write maintainable and reusable code.

    It just means that if you have a variable of a given type you can assign it to a value that is a subtype of that type.

    Because office is a subtype of building, I can pass it into this method. This is the substitution principle.

    class Building {
        @Override
        public String toString() {
            return("building");
        }
    }
    
    class Office extends Building {        
       
        @Override
        public String toString() {
            return ("office");
        }
    }
    
    public class Main {
        
        
        public static void main(String[] args) {
            Building building = new Building();        
            Office office = new Office();
            build(building);
            build(office);
            
            List<Building> buildings = new ArrayList();
            buildings.add(new Building());
            buildings.add(new Office());
            printBuildings(buildings);
            
            List<Office> offices = new ArrayList();
            offices.add(new Office());
            offices.add(new Office());
            printBuildings(offices);
            
        }
        
        static void build(Building building) {
            System.out.println("Constructing a new " + building.toString());
        }
        
        static void printBuildings(List<Building> buildings) {
            for(int i = 0; i < buildings.size(); i++) {
                System.out.println(i + 1 + ": " + buildings.get(i).toString());
            }
        }
        
    }
    
    

    It is also important to know when the substitution principle does not apply. You might think that because office is a subtype of building that a list of type office is a subtype of a list of type building. However, this isn’t actually the case.

    5 Using wildcards in generic programming

    A wildcard is essentially an unknown type, and can give you more flexibility when writing methods.

    To use a wildcard, I put a question mark and then write extends. (typing) Before the word building. This means that I can now pass in lists of any type that extends the building class.

    Wildcards can also be used to specify that super types can be used when a subtype is specified. In this main class, I also have a method called addHouseToList, which takes a list of houses as an argument and adds a new house to it. Currently, I can only pass in a list of houses to this method. But if I wanted to be able to pass in a list of Buildings, I can use wildcards again. This time, I’ve put a question mark and the word super in front of house, where I specify the type of list. Now, I can pass in a list of buildings to this method.

    class Building {
        public int numberOfRooms = 7;
        @Override
        public String toString() {
            return ("building");
        }
    
        public int getNumberOfRooms() {
            return numberOfRooms;
        }
    
        public void setNumberOfRooms(int numberOfRooms) {
            this.numberOfRooms = numberOfRooms;
        }
    }
    /*****************************************/
    public class House extends Building {
     
        public int numberOfRooms = 10;
        @Override
        public String toString() {
            return ("house");
        }
                
        public int getNumberOfRooms() {
            return numberOfRooms;
        }
        
        public void setNumberOfRooms(int numberOfRooms) {
            this.numberOfRooms = numberOfRooms;
        }
    }
    
    class Office extends Building {        
        
        @Override
        public String toString() {
            return ("office");
        }
    }
    
    public class Main {
        
        
        public static void main(String[] args) {
            
            // List of buildings
            List<Building> buildings = new ArrayList();
            buildings.add(new Building());
            buildings.add(new Building());
            printBuildings(buildings);
            
            // List of offices
            List<Office> offices = new ArrayList();
            offices.add(new Office());
            offices.add(new Office());
            printBuildings(offices);
    
            // List of houses
            List<House> houses = new ArrayList();
            houses.add(new House());
            houses.add(new House());
            printBuildings(houses);
            
            addHouseToList(houses);
            addHouseToList(buildings);        
            
        }
    
        static void printBuildings(List<? extends Building> buildings) {
            for(int i = 0; i < buildings.size(); i++) {
                System.out.println(buildings.get(i).toString() + " " + (i + 1));
            }
            System.out.println();
        }
        
        static void addHouseToList(List<? super House> buildings) {
            buildings.add(new House());
            System.out.println();
        }
    }
    

    If you are unsure about when to use extends and when to use super with wildcards, you can think about invariables and outvariables. In the printBuildings method, I am passing in a list which provides data which I use inside the method, so this in an invariable. With invariables, it makes sense to use extends. In the addHouseToList method, I am using the method to give additional data by adding to the list. So this is an outvariable. And in this case it makes sense to use super.

    Also note that it is generally a bad idea to use wildcards as return types for a method.

    展开全文
  • Java Generics and Collections
  • 仿制药 “ Understanding Java 8 Generics”视频课程的源代码
  • JavaCollections和Generics
  • generics:通用方法-源码

    2021-05-23 09:42:41
    generics旨在通过提供一组可以导入的泛型方法来帮助程序包作者减少依赖性。 例如,如果包作者希望为其对象包括一个tidy方法,则他们必须导入broom包才能这样做。 这会起作用,但可能会增加安装和/或测试软件包所需...
  • 泛型generics.zip

    2020-05-05 16:06:58
    泛型(Generics)是JDK5引入的一种参数化类型特性。它提供了编译时类型安全检测机制。其本质是参数类型,所操控的数据类型被指定为一个参数。泛型不存在于JVM虚拟机。泛型学习、泛型限定类型、泛型通配符、泛型继承。...
  • Swift Generics

    2018-06-22 08:09:51
    Swift Generics 首先来思考一下下面的一个例子: struct Buffer { var count: Int subscript(at: Int) -&gt; Int { get { return 1 } } } 复制代码 我们实例完一个Buffer对象,然后呢,就可以通过...
  • Java Generics Tutorial

    2012-01-20 01:00:37
    Java 的 Generics 简介。入门资料!
  • Adopt lightweight generics

    2021-01-10 05:49:32
    <div><p>Added lightweight generics annotations to collection-typed method and protocol signatures to streamline usage of these members in Swift. I forgot to take care of this as part of #1578. Again, ...
  • CSharp.10.Generics-源码

    2021-04-01 06:54:57
    CSharp.10.Generics
  • Ukeoppgaver_generics_collections
  • Generics Types 泛型学习笔记.pdf
  • Java 泛型 Generics

    2017-12-01 16:46:54
    Java 泛型 Generics
  • Generics in Java

    2019-12-05 13:32:04
    The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. It makes the code stable by detecting the bugs at compile time. 一、Advantages of Generics: Code Reuse We can ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 20,109
精华内容 8,043
关键字:

generics