【问题标题】:Generic class with generic arraylist具有泛型数组列表的泛型类
【发布时间】:2014-02-24 16:56:52
【问题描述】:

希望我能得到一些帮助。我正在尝试使用通用 arrayList 实例化一个通用对象 Student 作为成绩列表。我无法让我的 Add 方法正常工作。我不断收到一个空指针异常——这很明显,因为它被初始化为空——只是不确定我的 add 方法有什么问题。任何帮助将不胜感激。另外,这个任务的要求非常严格——我必须这样做。谢谢。

我有两个班级:第一个,学生:

import java.util.ArrayList;

public class Student <S>{

    private String name;
    private ArrayList<S> grades;



    private double average;


    // the constructor
    public Student (String studentName, ArrayList<S> studentGrades){
        name = studentName;
        grades = studentGrades;
    }

    // get the name
    public String getName() {
        return name;
    }

    //set the name
    public void setName(String name) {
        this.name = name;
    }

    // add a grade to the array
    public void addGrade(S n){

        grades.add(n);

    }

    // return a grade from the array. This will be used for the calculation.
    public S getGrade(int n){

        return grades.get(n);


    }

    // compute the average grade for each student
    public double computeAverage(){

        Double sum = 0.00;
        for(S grade : grades){ 

            if (grade instanceof Double){
            sum += (Double)grade;
            }
            if (grade instanceof Integer){
                sum += (Integer)grade;
            }
        }
        average = sum.doubleValue()/ grades.size();
        return average;

    }

    public String toString()
    {
        return name + "'s average grade is " + average;
    }
}

第二个,测试:

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        // create the studentList array
        ArrayList<Student> studentList = new ArrayList<Student>();
        HashMap<String, Student> studentMap = new HashMap<String, Student>();

        // the values for math.random to create the grades
        int min = 0;
        int max = 100;
        double dmin = 0.00;
        double dmax = 100.00;

        // initialize the variables

        ArrayList grades = null;

        //------------------------------------
        // Create the students (the method signature is wrong. It blows up regardless of what I try to add.)
        Student<Integer> Fred = new Student<Integer>("Fred", grades);   
        //null pointer exception. Also points to the add method in the student class.

        //-------------------------------------

        Student<Integer> Wilma = new Student<Integer>("Wilma", grades);
        Student<Double> Barney = new Student<Double>("Barney", grades);
        Student<Double> Betty = new Student<Double>("Betty", grades);   

        // add the random grades 
        for(int i = 0; i < 5; i++){
            Fred.addGrade((int) (Math.random() * (max - min) + min));
        }

        for(int i = 0; i < 5; i++){
            Wilma.addGrade((int) (Math.random() * (max - min) + min));
        }

        for(int i = 0; i < 5; i++){
            Barney.addGrade((double) (Math.random() * (dmax - dmin) + dmin));
        }

        for(int i = 0; i < 5; i++){
            Betty.addGrade((double) (Math.random() * (dmax - dmin) + dmin));
        }
        // add the students to the array list
        studentList.add(Fred);
        studentList.add(Wilma);
        studentList.add(Barney);
        studentList.add(Betty);

        studentMap.put(Fred.getName(), Fred);
        studentMap.put(Wilma.getName(), Wilma);
        studentMap.put(Barney.getName(), Barney);
        studentMap.put(Betty.getName(), Betty);


        //iterate through the list & print to the console
        Iterator<Student> itr = studentList.iterator();{
            while(itr.hasNext()){
                System.out.println(itr.next().<Student>toString());

                //Initialize the array to hold the key variables
                Set<String> mapKeys = studentMap.keySet();
                //mapKeys.add(something);

            }

        }

    }
}

【问题讨论】:

  • 你需要新建一个ArrayList。
  • 你为什么要让Student 类是通用的?我觉得没有必要。
  • 作业需要。
  • 感谢大家的帮助-非常感谢!

标签: java generics arraylist


【解决方案1】:

您需要初始化 ArrayList 等级。目前您正在传递一个空值。在该行中执行以下操作:

ArrayList grades = new ArrayList();

一个好的做法是在初始化 ArrayList 时使用泛型,但由于您的成绩似乎属于不同的类型,所以我跳过它。

【讨论】:

    【解决方案2】:

    您正在初始化 Test the Grades 为 null

    ArrayList grades = null;
    

    当您尝试添加成绩时

    Fred.addGrade(...);
    

    Student 中的内部代码是这样的

    grades.add(n);
    

    但是 Grades 被初始化为 null 并创建了一个 Null 异常。

    用正确的类型初始化成绩。

    例子:

    Student<Integer> Wilma = new Student<Integer>("Wilma", new ArrayList<Integer>());
    Student<Double> Barney = new Student<Double>("Barney", new ArrayList<Double>());
    Student<Double> Betty = new Student<Double>("Betty", new ArrayList<Double>());   
    

    【讨论】:

      【解决方案3】:

      在您的测试课程中,您有 ArrayList grades = null; - 使用前需要先创建成绩ArrayList并填入数据。

      【讨论】:

        【解决方案4】:

        你可以这样做:

        public class Student<S>
        {
            // declare array
            private final ArrayList<S> grades = new ArrayList<S>();
            private String name;
        
            // One arg constructor
            public Student(String name)
            {
                this.name = name;
            }
        
            // Two arg constructor
            public Student(String name, ArrayList<S> grades)
            {
                this(name);
                this.grades.addAll(grades);
            }
        
            // etc
        }
        

        【讨论】:

          【解决方案5】:

          在 Test 类中按以下方式编辑您的代码:

           Student<Integer> Fred = new Student<Integer>("Fred", new ArrayList<Integer>());   
              //null pointer exception. Also points to the add method in the student class.
          
              //-------------------------------------
          
           Student<Integer> Wilma = new Student<Integer>("Wilma", new ArrayList<Integer>());
           Student<Double> Barney = new Student<Double>("Barney", new ArrayList<Double>());
           Student<Double> Betty = new Student<Double>("Betty", new ArrayList<Double>());   
          

          希望,这会有所帮助。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多