java用顺序表实现通讯录设计
时间: 2024-05-06 07:20:06 浏览: 90
首先,我们需要定义通讯录的联系人实体类:
```java
public class Contact {
private String name;
private String phoneNumber;
private String email;
public Contact(String name, String phoneNumber, String email) {
this.name = name;
this.phoneNumber = phoneNumber;
this.email = email;
}
public String getName() {
return name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getEmail() {
return email;
}
@Override
public String toString() {
return "Name: " + name + ", Phone number: " + phoneNumber + ", Email: " + email;
}
}
```
接下来,我们需要实现顺序表类:
```java
public class ContactList {
private Contact[] contacts;
private int size;
public ContactList(int capacity) {
contacts = new Contact[capacity];
size = 0;
}
public int getSize() {
return size;
}
public void addContact(Contact contact) {
if (size == contacts.length) {
throw new RuntimeException("Contact list is full");
}
contacts[size++] = contact;
}
public Contact getContact(int index) {
if (index < 0 || index >= size) {
throw new RuntimeException("Invalid index");
}
return contacts[index];
}
public void removeContact(int index) {
if (index < 0 || index >= size) {
throw new RuntimeException("Invalid index");
}
for (int i = index; i < size - 1; i++) {
contacts[i] = contacts[i + 1];
}
contacts[size - 1] = null;
size--;
}
public void updateContact(int index, Contact contact) {
if (index < 0 || index >= size) {
throw new RuntimeException("Invalid index");
}
contacts[index] = contact;
}
public Contact[] getAllContacts() {
Contact[] result = new Contact[size];
for (int i = 0; i < size; i++) {
result[i] = contacts[i];
}
return result;
}
}
```
然后,我们可以在主函数中使用顺序表类来实现通讯录:
```java
public static void main(String[] args) {
ContactList contactList = new ContactList(10);
contactList.addContact(new Contact("Alice", "1234567890", "alice@example.com"));
contactList.addContact(new Contact("Bob", "2345678901", "bob@example.com"));
contactList.addContact(new Contact("Charlie", "3456789012", "charlie@example.com"));
contactList.removeContact(1);
contactList.updateContact(0, new Contact("Alice", "0987654321", "alice@example.com"));
Contact[] contacts = contactList.getAllContacts();
for (Contact contact : contacts) {
System.out.println(contact);
}
}
```
输出结果:
```
Name: Alice, Phone number: 0987654321, Email: alice@example.com
Name: Charlie, Phone number: 3456789012, Email: charlie@example.com
```
阅读全文