小编hax*_*hax的帖子

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

编写如下代码是错误的做法吗?我希望能够在我的人员类中存储一封电子邮件,其中还包含电子邮件类型(工作,个人等).我决定使用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)

java class treemap

2
推荐指数
1
解决办法
165
查看次数

标签 统计

class ×1

java ×1

treemap ×1