There are some points:
(1) Java array(use the symbol "[]") is a fixed size structure. It means you must specify the size(length) of the array when you create it. Like this:
int[] intArray = new int[10];
The purpose of the specific size is to tell Java compiler to allocate memory. Array is allocated in contiguous memory. Once the allocation has been done, its size could not be changed.(You can image there are other data "behind" the array, if the array is extende, will overlap the other data.)
(2) If you want to get a flexible data collection, for your adding/removing, you can use ArrayList
or LinkedList
. These Java built-in collections can be extended by themselves if needed.
What's more:
- ArrayList is implemented by Java array, it will automatically create a new larger array and copy the data into it when its Capacity is not enough. It has good performance in loop, access elements by index.
- LinkedList is implemented by Linked List. It has good performance in insert/remove elements.
- For Both lists, if you want to use the
remove(Object o)
correctly, you have to implement your object's public boolean equals(Object)
function.
Ref to the code:
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
public class ListTest {
public static void main(String[] args) {
List<Employee> employees = new LinkedList<Employee>();
// List<Employee> employees = new ArrayList<Employee>();
// Add 3 employees
employees.add(new Employee("Tom", "White", 10));
employees.add(new Employee("Mary", "Black", 20));
employees.add(new Employee("Jack", "Brown", 30));
// See what are in the list
System.out.println(employees);
// Remove the 2nd one.
employees.remove(new Employee("Mary", "Black", 20));
// See what are in the list after removing.
System.out.println(employees);
}
static class Employee {
private String firstName;
private String lastName;
private int age;
public Employee(String firstName, String lastName, int age) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public boolean equals(Object obj) {
if(super.equals(obj)) {
return true;
}
else {
if(obj.getClass() == Employee.class) {
Employee that = (Employee)obj;
return firstName.equals(that.getFirstName()) && lastName.equals(that.getLastName()) && (age == that.getAge());
}
else {
return false;
}
}
}
@Override
public String toString() {
return "Employee [firstName=" + firstName + ", lastName="
+ lastName + ", age=" + age + "]\n";
}
}
}