用处
一般是用在集合上 场景:现在把一个字符串通过list.add()放入在集合里面,这个值放到集合之后,就会失去本身的类型,只能是Object类型,此时如果想对刚才放入的字符串的值进行类型转换,会容易出现类型转换错误。泛型就是来解决这个问题。
在集合上使用泛型
List< String> list = new Arraylist < String> ( ) ;
list. add ( "a" ) ;
list. add ( "b" ) ;
list. add ( "c" ) ;
for ( int i= 0 ; i< list. size ( ) ; i++ ) {
String s = list. get ( i) ;
System. out. println ( s) ;
}
for ( String s1 : list) {
System. out. println ( s) ;
}
Iterator< String> it = list. iterator ( ) ;
while ( it. hasNext ( ) ) {
System. out. println ( it. next ( ) ) ;
}
在Set上使用泛型
@Test
public void testSet ( ) {
Set< String> set = new HashSet < String> ( ) ;
set. add ( "aaa" ) ;
set. add ( "bbb" ) ;
set. add ( "ccc" ) ;
for ( String s2 : set) {
System. out. println ( s2) ;
}
Iterator< String> it1 = set. iteerator ( ) ;
while ( it1. hasNext ( ) ) {
System. out. println ( it1. next ( ) ) ;
}
}
在Map上使用泛型
@Test
public void testMap ( ) {
Map< String, String> map = new HashMap < String, String> ( ) ;
map. put ( "aaa" , "123" ) ;
map. put ( "bbb" , "123" ) ;
map. put ( "ccc" , "123" ) ;
Set< String> sets = map. keySet ( ) ;
for ( String key : sets) {
String value = map. get ( key) ;
System. out. println ( key+ ":" + value) ;
}
Set< Entry< String, String> > sets1 = map. entrySet ( ) ;
for ( Entry< String, String> entry : sets1) {
String keyx = entry. getKey ( ) ;
String keyy = entry. getValue ( ) ;
System. out. println ( key+ ":" + value) ;
}
}