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的具体类 ...
随机推荐
- C#关于使用枚举遇到的问题----Type运算符使用的必要性
我定义了一个枚举AttributeName 然后写到下面代码: Enum .GetValues (AttributeName ): 毫无疑问的错了.别人说要加个Typeof 也就是Enum .GetV ...
- IP 转地址
1.需要 QQWry.Dat IP 地址数据库 2辅助类库 using System; using System.Collections.Generic; using System.IO; usin ...
- (转)如何将ecshop首页主广告位的flash轮播替换为js轮播
转之--http://www.ecshoptemplate.com/article-1710.html 这个ecshop很常见,因为现在比起flash难以修改,js更加符合人们的使用习惯,而默认ecs ...
- C#设计模式-创建型模式(转)
一.简单工厂模式 简单工厂模式Simple Factory,又称静态工厂方法模式.它是类的创建模式.是由一个工厂对象决定创建出哪一种产品类的实例,是不同的工厂方法模式的一个特殊实现. 优点: u 模式 ...
- 跟我学android-常用控件之EditText
EditText 是TextView的直接子类,它与TextView的区别在于,EditText可以接受用户输入. 下面通过一个实例来说明EditText的用法 实例:sina 微博的登录界面(注意, ...
- cmakelists 语法学习
1.项目最外层cmake编写:----------用于kdevelop编译器 project(filtering) cmake_minimum_required(VERSION 2.8) ————必须 ...
- android 9Path图片的使用
Android UI设计时,经常会使用图片作为背景,比如给按钮设置背景图片时,图片会默认缩放来适应整个按钮.但是有时这种缩放效果并不是我们所需求的.而我们只是希望缩放图片的特定位置,以此来保证按钮的视 ...
- w3wp异常
相信做ASP.NET中大型Web应用的人都碰到过OutOfMemoryException这个异常,对于这个问题我研究了很久,在微软的技术文档上也了解过此问题出现的原因,说实话,到目前我仍然没有完美的解 ...
- Python学习6.1_函数参数及参数传递
大多数编程语言都绕不开一个名词,那就是--函数(function).而函数很重要的部分则是参数(arguments)的使用.Python的参数传递总体来说是根据位置,传递对应的参数.阐述如下: 1.位 ...
- C++学习笔记3——类的封装(1)
封装: 1.把属性和方法进行封装. 2.对属性和方法进行访问控制. class和struct的区别: class和struct的唯一区别是默认的访问权限不一样.struct的默认访问权限是public ...