Ejemplo 1: argumento genérico java
staticvoidfromArrayToCollection(Object[] a,Collection<?> c)for(Object o : a)
c.add(o);// compile-time error
Ejemplo 2: genéricos java
// generic methodspublic<T>List<T>fromArrayToList(T[] a)returnArrays.stream(a).collect(Collectors.toList());publicstatic<T,G>List<G>fromArrayToList(T[] a,Function<T,G> mapperFunction)returnArrays.stream(a).map(mapperFunction).collect(Collectors.toList());// bounded genericspublic<TextendsNumber>List<T>fromArrayToList(T[] a)...//multiple bounds<TextendsNumber&Comparable>// upper bound wildcardspublicstaticvoidpaintAllBuildings(List<?extendsBuilding> buildings)...// lower bound wildcard<?superT>
Ejemplo 3: tipo genérico de Java
JavaGenericTypeNaming convention helps us understanding code easily and having a naming convention is one of the best practices of Java programming language. So generics also comes withits own naming conventions. Usually, type parameter names are single, uppercase letters tomake it easily distinguishable from java variables. The most commonly used type parameter names are:E – Element(used extensively by the JavaCollectionsFramework,for example ArrayList,Set etc.)K – Key(Used in Map)N – NumberT – TypeV – Value(Used in Map)S,U,V etc. – 2nd,3rd,4th types
Ejemplo 4: clase genérica java
publicinterfacePair<K,V>publicKgetKey();publicVgetValue();publicclassOrderedPair<K,V>implementsPair<K,V>privateK key;privateV value;publicOrderedPair(K key,V value)this.key = key;this.value = value;publicKgetKey()return key;publicVgetValue()return value;
Ejemplo 5: java define una clase genérica que produce
List list =newArrayList();
list.add("abc");
list.add(newInteger(5));//OKfor(Object obj : list)//type casting leading to ClassCastException at runtimeString str=(String) obj;
Ejemplo 6: java define una clase genérica que produce
List<String> list1 =newArrayList<String>();// java 7 ? List list1 = new ArrayList<>();
list1.add("abc");//list1.add(new Integer(5)); //compiler errorfor(String str : list1)//no type casting needed, avoids ClassCastException
Finalizando este artículo puedes encontrar las referencias de otros usuarios, tú asimismo tienes la libertad de dejar el tuyo si te gusta.
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)