Given:
1. import java.util.*,
2. public class TestGenericConversion{
3. public static void main(String[] args){
4. List list = new LinkedList();
5. list.add("one");
6. list.add("two");
7. System.out.print(((String)list.get(O)).length());
8. }
9. }
Refactor this class to use generics without changing the code's behavior.
1. import java.util.*,
2. public class TestGenericConversion{
3. public static void main(String[] args){
4. Place here
5. list.add("one");
6. list.add("two");
7. Place here
8. }
9. }
Code:
List list = new LinkedList();
System.out.print(list.get(0).length());
List<String> list = new LinkedList<String>();
System.out.print(list.get<String>(0).length());
List<String> list = new LinkedList();
System.out.print(<String>list.get(0).length());
List list = new LinkedList<String>();
System.out.print((List<String>)list.get(0).length());
答案:
1. import java.util.*,
2. public class TestGenericConversion{
3. public static void main(String[] args){
4. List<String> list = new LinkedList<String>();
5. list.add("one");
6. list.add("two");
7. System.out.print(list.get(0).length());
8. }
9. }
參考:12-3 泛型
--------------------------------------
5,6行加入String, 所以泛型要限定為String,
7.行, 以限定為String, 印出就不用再轉型.
沒有留言:
張貼留言