2017-07-02 58 views
1

我试图建立患者和过敏类,我感到困惑的setAllergies名单过敏,是否应该设计类:添加对象,而在Java中

this.allergies = allergies; 

allergies.add(allergies); 

Patient类:

public class Patient { 

    private List<Allergy> allergies; 

    public List<Allergy> getAllergies() { 
     return allergies; 
    } 

    public void setAllergies(List<Allergy> allergies) { 
     this.allergies = allergies; 
    } 

} 

过敏类:

public class Allergy { 
    private String name; 
    private Severity severity; 

    public Allergy(String name, Severity severity) { 
     this.name = name; 
     this.severity = severity; 
    } 

    public String getName() { 
     return name; 
    } 

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

    public Severity getSeverity() { 
     return severity; 
    } 

    public void setSeverity(Severity severity) { 
     this.severity = severity; 
    } 
} 
+0

'allergies.add(allergies)'没有任何意义。它甚至不会编译。 – shmosel

+0

@shmosel我的主要困惑是过敏类会返回过敏对象,那么它是如何通过this.allergies =过敏增加列表?过敏名单将从哪里来?因为过敏正在成为一个参数。 –

回答

1
allergies.add(allergies); 

向自身添加对象。
为什么要这样做? 此外,您不能将列表添加到列表add()
你必须使用addAll()


其实allergiesnull创建Patient实例时。

因此,这样做:allergies.invokeSomething(...);将抛出NullPointerException。 此外,“set”前缀具有覆盖/替换的语义,而不是添加。
所以你应该让你的方法,你的那一刻写道:现在

public void setAllergies(List<Allergy> allergies) { 
    this.allergies = allergies; 
} 

,如果你想提供一个方法来添加​​包含在allergies领域​​对象,你应该提供一个方法addAllergies()

public void addAllergies(List<Allergy> allergies) { 
    this.allergies.addAll(allergies); 
} 

而且你还要在其声明中初始化allergies场(或在Patient构造函数):

private List<Allergy> allergies = new ArrayList<>(); 
+0

我的主要困惑是过敏类会返回过敏对象,那么它是如何通过this.allergies =过敏增加列表?过敏名单将从哪里来?因为过敏正在成为一个参数。 –

+0

“从哪里来的过敏名单将来自哪里?”您提供了您想要在患者对象中设置的过敏列表作为参数。例如:'Patient p = new Patient(); List allergies = Arrays.asList(new Allergy(...),new Allergy(...)); p.setAllergies(过敏)' – davidxxx

+0

明白了。非常感谢。 –