long blogs

进一步有进一步惊喜


  • Home
  • Archive
  • Tags
  •  

© 2025 long

Theme Typography by Makito

Proudly published with Hexo

java泛型

Posted at 2019-07-07 笔记 java 

一、泛型的声明

使用”class 名称 <泛型列表>”声明一个泛型类。例如

1
2
3
4
5
public class Node<E>{
Node<E> previous;
E element;
Node<E> next;
}

声明了一个Node的泛型类。这个节点中的E可以是任何对象和接口。但不能是基本数据类型。

二、泛型的使用

(1) 泛型的使用和常用类的使用是一致。泛型列表中的泛型可以看作任何对象。可以做函数的参数,也可以做函数的返回值.例如自主实现LinkedList中的get函数。使用泛型作为返回值。

1
2
3
4
5
6
7
8
/**
* 通过index获得元素
* */
public E get(int index){
E re = null;
re = getNodeByIndex(index).element;
return re;
}

使用泛型作为返回值。自主实现HashTable中的get函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* get value by key
* */
public V get(K key){
Entry<K,V>[] tab = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
for(Entry<K,V> e = tab[index]; e!=null; e = e.next){
if((e.hash == hash) && e.key.equals(key)){
return e.value;
}
}
return null;
}

三、声明泛型数组

使用常规的数组声明方式声明泛型数组是会报错的。需要使用转型的声明。

1
Entry<K,V>[] newTable =(Entry<K, V>[]) new Entry[newCapacity];

Share 

 Previous post: maven环境变量配置 Next post: 图形图像处理 

© 2025 long

Theme Typography by Makito

Proudly published with Hexo