java中的泛型类及其使用
泛型的使用
集合的使用
一般集合的使用方式是:
比如有一个Person类
package com.atguigu.java; public class Person { // @Override
// public boolean equals(Object obj) {
// return false;
// } private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
} public Person() {
// TODO Auto-generated constructor stub
} public Person(String name, int age) {
super();
this.name = name;
this.age = age;
} // private static int init = 0; @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result; // return init++;
} @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
} @Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
} }
然后定义一个Person集合
package com.atguigu.java; import java.util.ArrayList;
import java.util.List; public class TestGerner { /**
* 对于集合没有泛型的情况:
* 1. 放入集合中的对象可以是任意类型.
* 2. 获取元素后, 需进行类型的强制转换.
* 为了类型转化是安全的,可能还需要instenceOf判断
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
List persons = new ArrayList();
persons.add(new Person("AA",12));
persons.add(new Person("BB",12));
persons.add(new Person("CC",12));
persons.add("string") Object obj = persons.get(0); Person person = (Person)persons.get(0); } }
对于集合没有泛型的情况:
* 1. 放入集合中的对象可以是任意类型.
* 2. 获取元素后, 需进行类型的强制转换.
如何把一个 list(集合) 中的内容限制为一个特定的数据类型呢?这就是 generics 背后的核心思想。这是上面程序片断的一个泛型版本:
public class TestGerner {
public static void main(String[] args) { List<Person> persons = new ArrayList<>(); persons.add(new Person("AA",12));
persons.add(new Person("BB",12));
persons.add(new Person("CC",12)); Person person = persons.get(0); //get的返回值就是Person类型
}
}
我们说 List 是一个带一个类型参数的泛型接口,本例中,类型参数是 Integer。我们在创建这个 List 对象的时候也指定了一个类型参数。
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/ package java.util; /**
* An ordered collection (also known as a <i>sequence</i>). The user of this
* interface has precise control over where in the list each element is
* inserted. The user can access elements by their integer index (position in
* the list), and search for elements in the list.<p>
*
* Unlike sets, lists typically allow duplicate elements. More formally,
* lists typically allow pairs of elements <tt>e1</tt> and <tt>e2</tt>
* such that <tt>e1.equals(e2)</tt>, and they typically allow multiple
* null elements if they allow null elements at all. It is not inconceivable
* that someone might wish to implement a list that prohibits duplicates, by
* throwing runtime exceptions when the user attempts to insert them, but we
* expect this usage to be rare.<p>
*
* The <tt>List</tt> interface places additional stipulations, beyond those
* specified in the <tt>Collection</tt> interface, on the contracts of the
* <tt>iterator</tt>, <tt>add</tt>, <tt>remove</tt>, <tt>equals</tt>, and
* <tt>hashCode</tt> methods. Declarations for other inherited methods are
* also included here for convenience.<p>
*
* The <tt>List</tt> interface provides four methods for positional (indexed)
* access to list elements. Lists (like Java arrays) are zero based. Note
* that these operations may execute in time proportional to the index value
* for some implementations (the <tt>LinkedList</tt> class, for
* example). Thus, iterating over the elements in a list is typically
* preferable to indexing through it if the caller does not know the
* implementation.<p>
*
* The <tt>List</tt> interface provides a special iterator, called a
* <tt>ListIterator</tt>, that allows element insertion and replacement, and
* bidirectional access in addition to the normal operations that the
* <tt>Iterator</tt> interface provides. A method is provided to obtain a
* list iterator that starts at a specified position in the list.<p>
*
* The <tt>List</tt> interface provides two methods to search for a specified
* object. From a performance standpoint, these methods should be used with
* caution. In many implementations they will perform costly linear
* searches.<p>
*
* The <tt>List</tt> interface provides two methods to efficiently insert and
* remove multiple elements at an arbitrary point in the list.<p>
*
* Note: While it is permissible for lists to contain themselves as elements,
* extreme caution is advised: the <tt>equals</tt> and <tt>hashCode</tt>
* methods are no longer well defined on such a list.
*
* <p>Some list implementations have restrictions on the elements that
* they may contain. For example, some implementations prohibit null elements,
* and some have restrictions on the types of their elements. Attempting to
* add an ineligible element throws an unchecked exception, typically
* <tt>NullPointerException</tt> or <tt>ClassCastException</tt>. Attempting
* to query the presence of an ineligible element may throw an exception,
* or it may simply return false; some implementations will exhibit the former
* behavior and some will exhibit the latter. More generally, attempting an
* operation on an ineligible element whose completion would not result in
* the insertion of an ineligible element into the list may throw an
* exception or it may succeed, at the option of the implementation.
* Such exceptions are marked as "optional" in the specification for this
* interface.
*
* <p>This interface is a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
*
* @param <E> the type of elements in this list
*
* @author Josh Bloch
* @author Neal Gafter
* @see Collection
* @see Set
* @see ArrayList
* @see LinkedList
* @see Vector
* @see Arrays#asList(Object[])
* @see Collections#nCopies(int, Object)
* @see Collections#EMPTY_LIST
* @see AbstractList
* @see AbstractSequentialList
* @since 1.2
*/ public interface List<E> extends Collection<E> {
// Query Operations /**
* Returns the number of elements in this list. If this list contains
* more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* @return the number of elements in this list
*/
int size(); /**
* Returns <tt>true</tt> if this list contains no elements.
*
* @return <tt>true</tt> if this list contains no elements
*/
boolean isEmpty(); /**
* Returns <tt>true</tt> if this list contains the specified element.
* More formally, returns <tt>true</tt> if and only if this list contains
* at least one element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
*
* @param o element whose presence in this list is to be tested
* @return <tt>true</tt> if this list contains the specified element
* @throws ClassCastException if the type of the specified element
* is incompatible with this list
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified element is null and this
* list does not permit null elements
* (<a href="Collection.html#optional-restrictions">optional</a>)
*/
boolean contains(Object o); /**
* Returns an iterator over the elements in this list in proper sequence.
*
* @return an iterator over the elements in this list in proper sequence
*/
Iterator<E> iterator(); /**
* Returns an array containing all of the elements in this list in proper
* sequence (from first to last element).
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this list. (In other words, this method must
* allocate a new array even if this list is backed by an array).
* The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all of the elements in this list in proper
* sequence
* @see Arrays#asList(Object[])
*/
Object[] toArray(); /**
* Returns an array containing all of the elements in this list in
* proper sequence (from first to last element); the runtime type of
* the returned array is that of the specified array. If the list fits
* in the specified array, it is returned therein. Otherwise, a new
* array is allocated with the runtime type of the specified array and
* the size of this list.
*
* <p>If the list fits in the specified array with room to spare (i.e.,
* the array has more elements than the list), the element in the array
* immediately following the end of the list is set to <tt>null</tt>.
* (This is useful in determining the length of the list <i>only</i> if
* the caller knows that the list does not contain any null elements.)
*
* <p>Like the {@link #toArray()} method, this method acts as bridge between
* array-based and collection-based APIs. Further, this method allows
* precise control over the runtime type of the output array, and may,
* under certain circumstances, be used to save allocation costs.
*
* <p>Suppose <tt>x</tt> is a list known to contain only strings.
* The following code can be used to dump the list into a newly
* allocated array of <tt>String</tt>:
*
* <pre>
* String[] y = x.toArray(new String[0]);</pre>
*
* Note that <tt>toArray(new Object[0])</tt> is identical in function to
* <tt>toArray()</tt>.
*
* @param a the array into which the elements of this list are to
* be stored, if it is big enough; otherwise, a new array of the
* same runtime type is allocated for this purpose.
* @return an array containing the elements of this list
* @throws ArrayStoreException if the runtime type of the specified array
* is not a supertype of the runtime type of every element in
* this list
* @throws NullPointerException if the specified array is null
*/
<T> T[] toArray(T[] a); // Modification Operations /**
* Appends the specified element to the end of this list (optional
* operation).
*
* <p>Lists that support this operation may place limitations on what
* elements may be added to this list. In particular, some
* lists will refuse to add null elements, and others will impose
* restrictions on the type of elements that may be added. List
* classes should clearly specify in their documentation any restrictions
* on what elements may be added.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
* @throws UnsupportedOperationException if the <tt>add</tt> operation
* is not supported by this list
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this list
* @throws NullPointerException if the specified element is null and this
* list does not permit null elements
* @throws IllegalArgumentException if some property of this element
* prevents it from being added to this list
*/
boolean add(E e); /**
* Removes the first occurrence of the specified element from this list,
* if it is present (optional operation). If this list does not contain
* the element, it is unchanged. More formally, removes the element with
* the lowest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
* (if such an element exists). Returns <tt>true</tt> if this list
* contained the specified element (or equivalently, if this list changed
* as a result of the call).
*
* @param o element to be removed from this list, if present
* @return <tt>true</tt> if this list contained the specified element
* @throws ClassCastException if the type of the specified element
* is incompatible with this list
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified element is null and this
* list does not permit null elements
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws UnsupportedOperationException if the <tt>remove</tt> operation
* is not supported by this list
*/
boolean remove(Object o); // Bulk Modification Operations /**
* Returns <tt>true</tt> if this list contains all of the elements of the
* specified collection.
*
* @param c collection to be checked for containment in this list
* @return <tt>true</tt> if this list contains all of the elements of the
* specified collection
* @throws ClassCastException if the types of one or more elements
* in the specified collection are incompatible with this
* list
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified collection contains one
* or more null elements and this list does not permit null
* elements
* (<a href="Collection.html#optional-restrictions">optional</a>),
* or if the specified collection is null
* @see #contains(Object)
*/
boolean containsAll(Collection<?> c); /**
* Appends all of the elements in the specified collection to the end of
* this list, in the order that they are returned by the specified
* collection's iterator (optional operation). The behavior of this
* operation is undefined if the specified collection is modified while
* the operation is in progress. (Note that this will occur if the
* specified collection is this list, and it's nonempty.)
*
* @param c collection containing elements to be added to this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws UnsupportedOperationException if the <tt>addAll</tt> operation
* is not supported by this list
* @throws ClassCastException if the class of an element of the specified
* collection prevents it from being added to this list
* @throws NullPointerException if the specified collection contains one
* or more null elements and this list does not permit null
* elements, or if the specified collection is null
* @throws IllegalArgumentException if some property of an element of the
* specified collection prevents it from being added to this list
* @see #add(Object)
*/
boolean addAll(Collection<? extends E> c); /**
* Inserts all of the elements in the specified collection into this
* list at the specified position (optional operation). Shifts the
* element currently at that position (if any) and any subsequent
* elements to the right (increases their indices). The new elements
* will appear in this list in the order that they are returned by the
* specified collection's iterator. The behavior of this operation is
* undefined if the specified collection is modified while the
* operation is in progress. (Note that this will occur if the specified
* collection is this list, and it's nonempty.)
*
* @param index index at which to insert the first element from the
* specified collection
* @param c collection containing elements to be added to this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws UnsupportedOperationException if the <tt>addAll</tt> operation
* is not supported by this list
* @throws ClassCastException if the class of an element of the specified
* collection prevents it from being added to this list
* @throws NullPointerException if the specified collection contains one
* or more null elements and this list does not permit null
* elements, or if the specified collection is null
* @throws IllegalArgumentException if some property of an element of the
* specified collection prevents it from being added to this list
* @throws IndexOutOfBoundsException if the index is out of range
* (<tt>index < 0 || index > size()</tt>)
*/
boolean addAll(int index, Collection<? extends E> c); /**
* Removes from this list all of its elements that are contained in the
* specified collection (optional operation).
*
* @param c collection containing elements to be removed from this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws UnsupportedOperationException if the <tt>removeAll</tt> operation
* is not supported by this list
* @throws ClassCastException if the class of an element of this list
* is incompatible with the specified collection
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if this list contains a null element and the
* specified collection does not permit null elements
* (<a href="Collection.html#optional-restrictions">optional</a>),
* or if the specified collection is null
* @see #remove(Object)
* @see #contains(Object)
*/
boolean removeAll(Collection<?> c); /**
* Retains only the elements in this list that are contained in the
* specified collection (optional operation). In other words, removes
* from this list all of its elements that are not contained in the
* specified collection.
*
* @param c collection containing elements to be retained in this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws UnsupportedOperationException if the <tt>retainAll</tt> operation
* is not supported by this list
* @throws ClassCastException if the class of an element of this list
* is incompatible with the specified collection
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if this list contains a null element and the
* specified collection does not permit null elements
* (<a href="Collection.html#optional-restrictions">optional</a>),
* or if the specified collection is null
* @see #remove(Object)
* @see #contains(Object)
*/
boolean retainAll(Collection<?> c); /**
* Removes all of the elements from this list (optional operation).
* The list will be empty after this call returns.
*
* @throws UnsupportedOperationException if the <tt>clear</tt> operation
* is not supported by this list
*/
void clear(); // Comparison and hashing /**
* Compares the specified object with this list for equality. Returns
* <tt>true</tt> if and only if the specified object is also a list, both
* lists have the same size, and all corresponding pairs of elements in
* the two lists are <i>equal</i>. (Two elements <tt>e1</tt> and
* <tt>e2</tt> are <i>equal</i> if <tt>(e1==null ? e2==null :
* e1.equals(e2))</tt>.) In other words, two lists are defined to be
* equal if they contain the same elements in the same order. This
* definition ensures that the equals method works properly across
* different implementations of the <tt>List</tt> interface.
*
* @param o the object to be compared for equality with this list
* @return <tt>true</tt> if the specified object is equal to this list
*/
boolean equals(Object o); /**
* Returns the hash code value for this list. The hash code of a list
* is defined to be the result of the following calculation:
* <pre>
* int hashCode = 1;
* for (E e : list)
* hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
* </pre>
* This ensures that <tt>list1.equals(list2)</tt> implies that
* <tt>list1.hashCode()==list2.hashCode()</tt> for any two lists,
* <tt>list1</tt> and <tt>list2</tt>, as required by the general
* contract of {@link Object#hashCode}.
*
* @return the hash code value for this list
* @see Object#equals(Object)
* @see #equals(Object)
*/
int hashCode(); // Positional Access Operations /**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException if the index is out of range
* (<tt>index < 0 || index >= size()</tt>)
*/
E get(int index); /**
* Replaces the element at the specified position in this list with the
* specified element (optional operation).
*
* @param index index of the element to replace
* @param element element to be stored at the specified position
* @return the element previously at the specified position
* @throws UnsupportedOperationException if the <tt>set</tt> operation
* is not supported by this list
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this list
* @throws NullPointerException if the specified element is null and
* this list does not permit null elements
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this list
* @throws IndexOutOfBoundsException if the index is out of range
* (<tt>index < 0 || index >= size()</tt>)
*/
E set(int index, E element); /**
* Inserts the specified element at the specified position in this list
* (optional operation). Shifts the element currently at that position
* (if any) and any subsequent elements to the right (adds one to their
* indices).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws UnsupportedOperationException if the <tt>add</tt> operation
* is not supported by this list
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this list
* @throws NullPointerException if the specified element is null and
* this list does not permit null elements
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this list
* @throws IndexOutOfBoundsException if the index is out of range
* (<tt>index < 0 || index > size()</tt>)
*/
void add(int index, E element); /**
* Removes the element at the specified position in this list (optional
* operation). Shifts any subsequent elements to the left (subtracts one
* from their indices). Returns the element that was removed from the
* list.
*
* @param index the index of the element to be removed
* @return the element previously at the specified position
* @throws UnsupportedOperationException if the <tt>remove</tt> operation
* is not supported by this list
* @throws IndexOutOfBoundsException if the index is out of range
* (<tt>index < 0 || index >= size()</tt>)
*/
E remove(int index); // Search Operations /**
* Returns the index of the first occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the lowest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*
* @param o element to search for
* @return the index of the first occurrence of the specified element in
* this list, or -1 if this list does not contain the element
* @throws ClassCastException if the type of the specified element
* is incompatible with this list
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified element is null and this
* list does not permit null elements
* (<a href="Collection.html#optional-restrictions">optional</a>)
*/
int indexOf(Object o); /**
* Returns the index of the last occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the highest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*
* @param o element to search for
* @return the index of the last occurrence of the specified element in
* this list, or -1 if this list does not contain the element
* @throws ClassCastException if the type of the specified element
* is incompatible with this list
* (<a href="Collection.html#optional-restrictions">optional</a>)
* @throws NullPointerException if the specified element is null and this
* list does not permit null elements
* (<a href="Collection.html#optional-restrictions">optional</a>)
*/
int lastIndexOf(Object o); // List Iterators /**
* Returns a list iterator over the elements in this list (in proper
* sequence).
*
* @return a list iterator over the elements in this list (in proper
* sequence)
*/
ListIterator<E> listIterator(); /**
* Returns a list iterator over the elements in this list (in proper
* sequence), starting at the specified position in the list.
* The specified index indicates the first element that would be
* returned by an initial call to {@link ListIterator#next next}.
* An initial call to {@link ListIterator#previous previous} would
* return the element with the specified index minus one.
*
* @param index index of the first element to be returned from the
* list iterator (by a call to {@link ListIterator#next next})
* @return a list iterator over the elements in this list (in proper
* sequence), starting at the specified position in the list
* @throws IndexOutOfBoundsException if the index is out of range
* ({@code index < 0 || index > size()})
*/
ListIterator<E> listIterator(int index); // View /**
* Returns a view of the portion of this list between the specified
* <tt>fromIndex</tt>, inclusive, and <tt>toIndex</tt>, exclusive. (If
* <tt>fromIndex</tt> and <tt>toIndex</tt> are equal, the returned list is
* empty.) The returned list is backed by this list, so non-structural
* changes in the returned list are reflected in this list, and vice-versa.
* The returned list supports all of the optional list operations supported
* by this list.<p>
*
* This method eliminates the need for explicit range operations (of
* the sort that commonly exist for arrays). Any operation that expects
* a list can be used as a range operation by passing a subList view
* instead of a whole list. For example, the following idiom
* removes a range of elements from a list:
* <pre>
* list.subList(from, to).clear();
* </pre>
* Similar idioms may be constructed for <tt>indexOf</tt> and
* <tt>lastIndexOf</tt>, and all of the algorithms in the
* <tt>Collections</tt> class can be applied to a subList.<p>
*
* The semantics of the list returned by this method become undefined if
* the backing list (i.e., this list) is <i>structurally modified</i> in
* any way other than via the returned list. (Structural modifications are
* those that change the size of this list, or otherwise perturb it in such
* a fashion that iterations in progress may yield incorrect results.)
*
* @param fromIndex low endpoint (inclusive) of the subList
* @param toIndex high endpoint (exclusive) of the subList
* @return a view of the specified range within this list
* @throws IndexOutOfBoundsException for an illegal endpoint index value
* (<tt>fromIndex < 0 || toIndex > size ||
* fromIndex > toIndex</tt>)
*/
List<E> subList(int fromIndex, int toIndex);
}
泛型接口
泛型类型参数或返回值
比如在Interface List<E> 下面会有两个方法(可以参见下面的泛型方法)
Object[] |
toArray()
Returns an array containing all of the elements in this list in proper sequence (from first to last element).
|
<T> T[] |
toArray(T[] a)
Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
|
区别是什么呢?
public class TestGerner {
public static void main(String[] args) { List<Person> persons = new ArrayList<>();
persons.add(new Person("AA",12));
persons.add(new Person("BB",12));
persons.add(new Person("CC",12));
//这种写法是不对的,因为toArray()返回的是object类型,而object类型是不能转化为数组型的,除非一个个转化
//Person [] personArray = (Person[]) persons.toArray();
//System.out.println(personArray.length); //这种写法是对的,要传入一个泛型数组,只要是数组即可,所以new Person[0]是可以的
//这样返回值就是对于泛型对应类型的一个数组
Person [] personArray = persons.toArray(new Person[0]);
System.out.println(personArray.length);
}
}
Map的遍历
遍历Map的方式:
- 得到键的集合,然后通过对键集合的遍历得到值
- 直接得到值的集合
- 泛型的方式
public class TestGerner {
public static void main(String[] args) { List<Person> persons = new ArrayList<>();
persons.add(new Person("AA",12));
persons.add(new Person("BB",34));
persons.add(new Person("CC",56)); Map<String,Person> personMap = new HashMap<String,Person>();
personMap.put("AA",persons.get(0));
personMap.put("BB",persons.get(1));
personMap.put("CC",persons.get(2)); for(Map.Entry<String,Person> entry: personMap.entrySet()){
System.out.println( entry.getKey() + ":" + entry.getValue());
}
}
} 结果是
AA:Person [name=AA, age=12]
BB:Person [name=BB, age=34]
CC:Person [name=CC, age=56]
定义简单的泛型类
类型参数在整个类的声明中可用,几乎是所有可以使用其他普通类型的地方都可以用
package com.atguigu.java; public class DAO<T> {
/**
* 泛型类
* 声明类的同时声明泛型类型
* 1.方法的返回值可以是使用声明的泛型类型
* 2.方法的参数也可以是声明类的泛型类型
* 3.方法体内可以使用泛型类型
*/
public T get(Integer id){
return null;
} public void save(T entity){
}
}
类型参数就跟在方法或构造函数中普通的参数一样。就像一个方法有形式参数来描述它操作的参数的种类一样,一个泛型声明也有形式类型参数。当一个方法被调用,实参(actual arguments)替换形参,方法体被执行。当一个泛型声明被调用,实际类型参数(actual type arguments)取代形式类型参数。
相当于声明的时候public class DAO<T> T是一个形参,而使用的时候DAO<Person> dao = new DAO<>(); 相当于传入一个实参
泛型和子类继承
如果 Foo 是 Bar 的一个子类型(子类或者子接口),而 G 是某种泛型声明,那么 G<Foo>是 G<Bar>的子类型并不成立!!
public class TestGerner {
public static void main(String[] args) {
//String 为 Object 类型的子类, 则 String[] 也是 Object[] 的子类
Object [] objs = new String[]{"AA", "BB"}; //String 为 Object 类型的子类, 则 List<String> 不是 List<Object> 的子类!
//List<String> strList = new ArrayList<String>();
//List<Object> objList = strList;
//原因在于strList中存取的都是String,而objList中却可以存放非String类型,取出来的时候会有问题,与泛型基本原则相悖
//泛型原则是某个集合对象只能放某个类型,不能放其他类型
}
}
为了处理这种情况,考虑一些更灵活的泛型类型很有用。
通配符
Collection<?>(发音为:"collection of unknown"),就是,一个集合,它的元素类型可以匹配任何类型。显然,它被称为通配符。
package com.atguigu.java;
//构造一个Student类,继承与Person public class Student extends Person{
private String school; public Student(String name,int age,String school) {
super(name,age);
this.school = school;
} public String getSchool() {
return school;
} @Override
public String toString() {
return "Student [school=" + school + "]";
} public void setSchool(String school) {
this.school = school;
} }
定义一个Student类
public class TestGerner {
//定义一个打印信息方法
public static void printPersonInfo(List<Person> persons){
for(Person person:persons){
System.out.println(person);
}
}
public static void main(String[] args) { List<Person> persons = new ArrayList<>();
persons.add(new Person("AA",12));
persons.add(new Person("BB",34));
persons.add(new Person("CC",56));
//这里调用是没有问题的
printPersonInfo(persons); List<Student> stus = new ArrayList<>();
stus.add(new Student("TT",22,"TInghua"));
//这里调用是不对的
//因为Student是Person的子类,但是List<Student>却不是List<Person>的子类
printPersonInfo(stus);
}
}
把printPersonInfo改成通配符方法
//使用通配符方法
public static void printPersonInfo(List<? extends Person> persons){
for(Person person:persons){
System.out.println(person);
}
} /**
* 结果是
* Person [name=AA, age=12]
* Person [name=BB, age=34]
* Person [name=CC, age=56]
* Student [school=TInghua]
*/
这样的话,printPersonInfo方法可以接受Person类以及Person子类
上面的例子是一个有上限通配符,如果没有上限,就是任意通配符
//任意通配符方法
//取出来的时候,只能是Object类
public static void printPersonInfo(List<?> persons){
for(Object person:persons){
System.out.println(person);
}
}
但是,将多种类型加入到同一个泛型集合中中不是类型安全的
add 方法有类型参数 E 作为集合的元素类型。我们传给 add 的任何参数都必须是一个未知类型的子类。因为我们不知道那是什么类型,所以我们无法传任何东西进去。唯一的例外是 null,它是所有类型的成员。
//通配符的安全性问题
public static void printPersonInfo(List<? extends Person> persons){
//加入null是可行的
persons.add(null);
//这句话编译出错,因为不能确定Person中到底是什么类型(可能是Person类型,也可能是其子类型)
//所以往里面添加任何类型元素都是不行的
persons.add(new Person("DD",78)); //向外取数据是合法的
//我们可以调用 get()方法并使用其返回值。返回值是一个未知的类型,但是我们知道,这里它总是一个Person
for(Person person:persons){
System.out.println(person);
}
}
泛型方法
在非泛型类里面,可以单独的定义泛型方法
在泛型类里,泛型方法也可以使用类声明之外的泛型
package com.atguigu.java; import java.util.ArrayList;
import java.util.Collection; public class TestGerner {
/**
* 泛型方法: 在方法声明时, 同时声明泛型. 在方法的返回值, 参数列表以及方法体中都可以使用泛型类型.
* public static <T> T get(Integer id){
* T result = null;
* return result;
* }
* 把指定类型的数组中的元素放入到指定类型的集合中
*/
public static <T> void fromArrayToCollection(T [] objs, Collection<T> coll){ } public static void main(String[] args) { String[] objs2 = new String[]{"AA", "BB", "CC"};
Collection<String> coll2 = new ArrayList<>();
fromArrayToCollection(objs2, coll2); Person[] objs3 = new Person[]{new Person("AA", 12)};
Collection<Person> coll3 = new ArrayList<>();
fromArrayToCollection(objs3, coll3);
}
}
实例化泛型对象的方法
http://blog.csdn.net/shigaofei1/article/details/6546416
java中的泛型类及其使用的更多相关文章
- Java中的泛型类和泛型方法区别和联系
泛型的概念大家应该都会,不懂的百度或者google,在java中泛型类的定义较为简单 <span style="font-size:18px;"><span st ...
- java中的泛型类和泛型方法
1.泛型是什么? 泛型(Generic type 或者 generics)是对 Java 语言的类型系统的一种扩展,以支持创建可以按类型进行参数化的类. 可以在集合框架(Collection fram ...
- 0072 Java中的泛型--泛型是什么--泛型类--泛型方法--擦除--桥方法
什么是泛型,有什么用? 先运行下面的代码: public class Test { public static void main(String[] args) { Comparable c=new ...
- Java中的泛型 (上) - 基本概念和原理
本节我们主要来介绍泛型的基本概念和原理 后续章节我们会介绍各种容器类,容器类可以说是日常程序开发中天天用到的,没有容器类,难以想象能开发什么真正有用的程序.而容器类是基于泛型的,不理解泛型,我们就难以 ...
- java中的泛型的使用与理解
什么是泛型? 泛型是程序设计语言的一种特性.允许程序员在强类型程序设计语言中编写 体验泛型代码时定义一些可变部份,那些部份在使用前必须作出指明.各种程序设计语言和其编译器.运行环境对泛型的支持均不一样 ...
- java中的泛型和sql中的索引
sql中的索引 索引:好处查询的速度快,被删除,修改,不会对表产生影响,作用是加速查询: 一种典型的数据库对象 作用:提交数据的查询效率,尤其对一些数据量很大的表 索引是用来为表服务的 索引是orac ...
- Java中的逆变与协变
看下面一段代码 Number num = new Integer(1); ArrayList<Number> list = new ArrayList<Integer>(); ...
- [JavaCore]JAVA中的泛型
JAVA中的泛型 [更新总结] 泛型就是定义在类里面的一个类型,这个类型在编写类的时候是不确定的,而在初始化对象时,必须确定该类型:这个类型可以在一个在里定义多个:在一旦使用某种类型,在类方法中,那么 ...
- Java中的泛型方法
泛型是什么意思在这就不多说了,而Java中泛型类的定义也比较简单,例如:public class Test<T>{}.这样就定义了一个泛型类Test,在实例化该类时,必须指明泛型T的具体类 ...
随机推荐
- 详谈typedef的用法
我们都知道typedef是类型重定义,既然是重定义就不可能出现新的数据类型,只是将已有的数据类型进行换个名字而已,但是这有什么用呢?可能我们学的时候,给的例子都是:typedef int INT; 然 ...
- Python简易爬虫
经常需要下载论文,每次都需要去网页上搜索,然后点击下载,实在麻烦,正好最近刚入门Python,心血来潮,想着写一个爬虫 经过一天查阅资料,基本算是完成了,但是还是不足,比如对知网和万方暂时还不行,但是 ...
- Android中px、dp、sp的区别
px: 即像素,1px代表屏幕上一个物理的像素点: px单位不被建议使用,因为同样100px的图片,在不同手机上显示的实际大小可能不同,如下图所示(图片来自android developer guid ...
- css标签选择器
/*标签选择器*/ input[type="text"] { width: 60%; } </style>
- Content-Disposition的使用和注意事项
转载:http://www.cnblogs.com/jzaileen/articles/1281025.html 最近不少Web技术圈内的朋友在讨论协议方面的事情,有的说web开发者应该熟悉web相关 ...
- SQLServer2008收缩数据库日志
-- Set to SIMPLE mode ALTER DATABASE [DATABASE_NAME] SET RECOVERY SIMPLE; -- Shrink the db ); -- Set ...
- Css3中的响应式布局的应用
Media Queries直译过来就是“媒体查询”,在我们平时的Web页面中head部分常看到这样的一段代码: <link href="css/reset.css" rel= ...
- 初涉JavaScript模式 (7) : 原型模式 【三】
组合使用构造函数模式和原型模式 上篇,我们提到了原型模式的缺点,就是每个实例不能拥有自己的属性,因为纯原型模式所有的属性都是公开给每个实例的,故我们可以组合使用构造函数模式和原型模式.构造函数用来定义 ...
- 广东移动NGBOSS系统话费查询
基于很多客户的需要 现承接广东移动NGBOSS华为系统的各项功能开发 承接广东深圳.佛山.东莞.广州.惠州.汕头.湛江移动NGBOSS的全球通开户,批量话费查询.缴费,号码导出等功能开发. 有需要者联 ...
- 每日一算法【one】
//有一个数组 {1,2,3,4,5,6,7,8,9,12,13,45,67,89,99,101,111,123,134,565,677} 查找数组中是否有指定的某一个数. /** *------- ...