Select Git revision
git_tutorial.md
DynArray.java 2.02 KiB
public class DynArray {
private final int basev = 10;
private int size = 0;
private Contact[] array;
private int capacity;
public DynArray(Contact[] a) {
this.size = a.length;
this.capacity = this.basev;
this.array = new Contact[this.capacity];
copy_content(a, this.array);
}
public DynArray() {
this.array = new Contact[this.capacity];
this.size = 0;
}
public void append(Contact[] a) {
make_sure_size(a); // REALLOC IF NEEDED
this.size += a.length;
int s = this.size;
// Add the new values
for (int i = s; i < s + a.length; i++) {
// System.out.println("arr[" + (i - a.length) + "] = " + a[i - s]);
this.array[i - a.length] = a[i - s];
}
}
public void pop() {
if (this.size < 1) {
System.err.println("Cannot remove from an epmty list");
return;
}
this.size--;
}
public void make_sure_size(Contact[] a) {
if ((this.size + a.length) > this.capacity) // Overflow?
{
// Realloc new array
this.capacity *= 2;
Contact[] new_arr = new Contact[this.capacity];
copy_content(this.array, new_arr);
this.array = new_arr; // Copy pointer
}
}
public void make_sure_size(Contact a) {
if ((this.size + 1) > this.capacity) // Overflow?
{
// Realloc new array
this.capacity *= 2;
Contact[] new_arr = new Contact[this.capacity];
copy_content(this.array, new_arr);
this.array = new_arr; // Copy pointer
}
}
public void show_it() {
System.out.println(this.toString());
}
public String toString() {
String s = "";
for (int i = 0; i < this.size; i++) {
s = s.concat(array[i].toShortString());
s = s.concat(",\n");
}
return s;
}
public boolean isEmpty() {
return size == 0;
}
private static void copy_content(Contact[] source, Contact[] dest) {
// System.out.println("Source lenght" + source.length);
// System.out.println("Dest lenght" + dest.length);
if (source.length > dest.length) {
throw new Error("Cannot copy : second array smaller than first");
}
for (int i = 0; i < source.length; i++) {
dest[i] = source[i];
}
}
}