我正在通过构建一个简单的目录来练习java.我有4个课程.这些是:
人
地址
联系
识别TestClass
我已经完成了这个系统的创建,它按照我想要的方式工作.我通过为Person,Address和Contact制作3个不同的数组来做到这一点.要将Person,Address和Contact链接在一起,我将它们放在具有相同索引号的相应数组上.(不是将它们链接在一起,只是一种在编辑人员时知道要访问哪个地址或联系人的方法).
但现在,我想优化它.我想创建一个HashMap来保存一个人,其中包含地址和联系人.请参阅下面的代码以获取更多信息.
Person.class
public class Person { private long Id; private firtName; private Address address; private Contact contact; //some setter and getter methods public Person(Address address, Contact contact) { this.address = address; this.contact = contact; } }
Address.class
public class Address { private String street; private String city; private String province; //some setter and getter methods }
Contact.class
public class Contact { private long Phone; private String Email; //some setter and getter methods }
testClass.class
public class testClass { public static void main(String[] args) { HashMapperson = new HashMap (); person.put(1, new Person(new Address(), new Contact))); person.get(1).setStreet("place"); } }
我的问题是,在testClass中的这行代码
person.get(1).setStreet("place");
有没有办法直接访问/编辑该人的地址或联系人而无需创建单独的数组或方法?
private Address address; private Contact contact;
如果您要创建这些public
而不是private
您将能够直接访问它们,如下所示:
Person person = new Person(new Address(), new Contact()); Person p = person.get(1); String city = p.address.getCity(); String email = p.contact.getEmail();
但是这违反了封装原则(您应该隐藏内部字段并仅允许通过方法访问).
相反,您应该按如下方式创建您的人员类:
public class Person { private long Id; private firtName; private Address address; private Contact contact; //some setter and getter methods public Person(Address address, Contact contact) { this.address = address; this.contact = contact; } public Address getAddress() { return address; } public Contact getContact() { return contact; } }
并通过访问
Person p = person.get(1); String city = p.getAddress().getCity(); String email = p.getContact().getEmail();