SLIDE 13 2005 JavaOneSM Conference | Session TS-5627 | 25
Using a Predefined Generic Type
- Demonstrates a key benefit of generics
- Source code is more readable and precise
than without generics
publ i c st at i c Col l ect i on<St r i ng> r em
- veDi r ect or y( Col l ect i on<Fi l e> absol ut eFi l es,
St r i ng di r ect or yToBeRem
Pat h) { Col l ect i on<St r i ng> r el at i veFi l eNam es = new HashSet <St r i ng> ( ) ; I t er at or <Fi l e> i t er = absol ut eFi l es. i t er at or ( ) ; whi l e ( i t er . hasNext ( ) ) { r el at i veFi l eNam
Fi l eUt i l i t y. r el at i vePat h( i t er . next ( ) . get Pat h( ) , di r ect or yToBeRem
Pat h) ) ; } r et ur n r el at i veFi l eNam es; }
2005 JavaOneSM Conference | Session TS-5627 | 26
Same Code Without Generics
- It’s difficult to tell what the collections contain
publ i c st at i c Col l ect i on r em
- veDi r ect or y( Col l ect i on absol ut eFi l es,
St r i ng di r ect or yToBeRem
Pat h) { Col l ect i on r el at i veFi l eNam es = new HashSet ( ) ; I t er at or i t er = absol ut eFi l es. i t er at or ( ) ; whi l e ( i t er . hasNext ( ) ) { r el at i veFi l eNam
Fi l eUt i l i t y. r el at i vePat h( ( ( Fi l e) i t er . next ( ) ) . get Pat h( ) , di r ect or yToBeRem
Pat h) ) ; } r et ur n r el at i veFi l eNam es; }