某些类的定义如类ArrayList<E>和类HashMap<K,V>后面那个<>究竟是怎么个语法啊。
因为E,K,V这三个参数既不是类也不是基本数据类型,java怎么就能解析它们呢?我用其它字母代替它定义会有什么结果?
比如: ArrayList<S>和类HashMap<G,W>?
注意:我也明白<>中参数的意义,E指元素,K指key键索引,V指vaule键值。
但是是不是自己定义的类也可以用这个语法。
哪位大侠能不能用自己定义的类来解释一下这个语法?
因为E,K,V这三个参数既不是类也不是基本数据类型,java怎么就能解析它们呢?我用其它字母代替它定义会有什么结果?
比如: ArrayList<S>和类HashMap<G,W>?
注意:我也明白<>中参数的意义,E指元素,K指key键索引,V指vaule键值。
但是是不是自己定义的类也可以用这个语法。
哪位大侠能不能用自己定义的类来解释一下这个语法?
楼主【redbridge】截止到2008-06-25 23:45:08的历史汇总数据(不包括此帖):
发帖数:20 发帖分:650
结贴数:19 结贴分:640
未结数:1 未结分:10
结贴率:95.00 % 结分率:98.46 %
值得尊敬
比如ArrayList<E> list=new ArrayList<String>();
HashMap<K,V> map=new HashMap<String,Long>();
由于jdk1.4里面提供的arraylist只能对object进行操作,存取需要强制转换很麻烦,1.5的时候就增加了泛型来解决这个问题
ArrayList<String>,这样的好处是当你用ArrayList的方法返回其中的元素时,返回的元素类型本身就已经是String类型了,而JAVA1.5以前没有使用泛型,返回的类型就是Object,这样的话还得你自己强制转换成String.HashMap同理.
http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
HelloWorld<String> hello = new HelloWorld<String>();
// 由于指定了泛型参数为 String 类型,因此 T 就使用 String 来代替了
// setName 中的参数只能是 String 类型的了
hello.setName("hi");
System.out.println(hello.getName());
HelloWorld<Integer> integer = new HelloWorld<Integer>();
integer.setName(new Integer(5));
System.out.println(integer.getName());
}
}class HelloWorld<T> {
private T name;
public T getName() {
return name;
}
public void setName(T name) {
this.name = name;
}
}
请教1:其参数(Map<? extends K, ? extends V> m)是什么意思呢?怎么解析?
请教2:后面的for循环又如何解析呢?
for (Iterator<? extends Map.Entry<? extends K, ? extends V>> i = m.entrySet().iterator(); i.hasNext(); ) {
Map.Entry<? extends K, ? extends V> e = i.next();
put(e.getKey(), e.getValue());
}
public void putAll(Map<? extends K, ? extends V> m) {
int numKeysToBeAdded = m.size();
if (numKeysToBeAdded == 0)
return; /*
* Expand the map if the map if the number of mappings to be added
* is greater than or equal to threshold. This is conservative; the
* obvious condition is (m.size() + size) >= threshold, but this
* condition could result in a map with twice the appropriate capacity,
* if the keys to be added overlap with the keys already in this map.
* By using the conservative calculation, we subject ourself
* to at most one extra resize.
*/
if (numKeysToBeAdded > threshold) {
int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
if (targetCapacity > MAXIMUM_CAPACITY)
targetCapacity = MAXIMUM_CAPACITY;
int newCapacity = table.length;
while (newCapacity < targetCapacity)
newCapacity <<= 1;
if (newCapacity > table.length)
resize(newCapacity);
} for (Iterator<? extends Map.Entry<? extends K, ? extends V>> i = m.entrySet().iterator(); i.hasNext(); ) {
Map.Entry<? extends K, ? extends V> e = i.next();
put(e.getKey(), e.getValue());
}
}
和for(int i=0;i++;)类比,Iterator <? extends Map.Entry <? extends K, ? extends V>> i = m.entrySet().iterator()就相当于int i=0,而i.hasNext()就相当于i++,这是一个很普通的循环啊!!!
PS:楼主这可是一帖多问啊!!!