使用TreeMap作为Person对象类中的属性

hax*_*hax 2 java class treemap

编写如下代码是错误的做法吗?我希望能够在我的人员类中存储一封电子邮件,其中还包含电子邮件类型(工作,个人等).我决定使用TreeMap.我知道所有变量都是私有的并使用getter和setter来操作它们是一种好习惯,但是通过直接使用TreeSet方法而不是我自己的Person类来操作我的TreeSet是错误的吗?换句话说,这是一种有效的可接受的方式吗?代码似乎工作正常.

public class Person {
  private String firstName;
  private String lastName;
  private String note;
  TreeMap<String, String> phoneNum = new TreeMap<String, String>();

  // Assume constructor method contains firstName & lastName and there are
  // getters and setters for both
}

public class MainDriver {
  public static void main(String[] args) {
    Person p1 = new Person("John", "Smith");

    p1.phoneNum.put("jsmith@gmail.com", "School");
    p1.phoneNum.put("jsmith19@gmail.com", "Personal");

    Person p2 = new Person("Sam", "Johnson");

    p2.phoneNum.put("samjohn@gmail.com", "Personal");
    p2.phoneNum.put("samjohnson", "Work");

    System.out.println(p1.phoneNum);
    System.out.println(p2.phoneNum);
  }
}

Output:
{jbillingham@gmail.com=Personal, jebillingham3@gmail.com=School}
{samsamyoussef=Work, samyou@gmail.com=Personal}
Run Code Online (Sandbox Code Playgroud)

Syn*_*sso 5

它并不可怕,但它使功能羡慕(代码气味,对象直接使用其他对象的字段).

问题是你只希望启用添加电子邮件地址Person,但实际上你公开了所有的操作TreeMap.方法如ceilingKey,tailMapremove.为了限制可以执行的操作,您应该完全封装字段并提供显式方法.