正 文

Eclipse 3.1中的Java泛型支持


www.7dspace.com  更新日期:2005-12-10 2:10:56  七度空间


  从特定类型向泛型转换

  请考虑清单 1 中的简单类,它创建了一个 Employee 和 Manager 对象的列表(Manager 扩展自 Employee),将他们打印出来,给他们涨工资后再打印出来。

清单 1. HR 类

package com.nealford.devworks.generics.generics; 

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class HR {

    public HR() {
        List empList = new ArrayList(5);
        empList.add(new Employee("Homer", 200.0, 1995));
        empList.add(new Employee("Lenny", 300.0, 2000));
        empList.add(new Employee("Waylon", 700.0, 1965));
        empList.add(new Manager("Monty", 2000.0, 1933,
                (Employee) empList.get(2))); 

        printEmployees(empList);

        System.out.println("----- Give everyone a raise -----");
        for (int i = 0; i < empList.size(); i++)
            ((Employee) empList.get(i)).applyRaise(5);  

        printEmployees(empList);  

        System.out.println("The maximum salary for any employee is "+ 
                Employee.MAX_SALARY);  

        System.out.println("Sort employees by salary"); 
        Collections.sort(empList); 
        printEmployees(empList);  

        System.out.println("Sort employees by name"); 
        Collections.sort(empList, new Employee.NameComparer()); 
        printEmployees(empList);  

        System.out.println("Sort employees by hire year"); 
        Collections.sort(empList, Employee.getHireYearComparator()); 
        printEmployees(empList);  

    } 

    public void printEmployees(List emps) { 
        for (int i = 0; i < emps.size(); i++)  
            System.out.println(emps.get(i)); 
    }  

    public static void main(String[] args) { 
        new HR(); 
    } 
}

  如果您打开了 Java 5 支持,编译这段代码会出现多种警告信息。

5页,页码:[1] [2] [3] [4] [5] 

上一篇:VB.Net编程实现Web Service的基础
下一篇:巧用AutoCAD阵列做法兰零件排料图
作者:Neal Ford  来源:ibm ( 责任编辑:7dspace )
收藏此页】【打印】【关闭
站 内 搜 索
 

热 点 导 读
特 别 推 荐