我搜索了互联网,我无法找到我的问题的答案。我正在编写我自己的数组列表结构。我希望使它成为一个有序的数组,它将接收一个来自联系人类的对象,并按姓氏排序。我有这个到目前为止,但我不能管理如何做add()方法。与可比较的Java ArrayList
public class SortedArrayList <E extends Comparable<E>> implements SortedList<E> {
private int currentSize;
private E elements[];
@SuppressWarnings("unchecked")
public SortedArrayList(int initialCapacity){
if(initialCapacity < 1){
throw new IllegalArgumentException("Need at least one element");
}
this.currentSize = 0;
this.elements = (E[]) new Object[initialCapacity];
}
@Override
public Iterator<E> iterator() {
// TODO Auto-generated method stub
return new ListIterator<E>();
}
@Override
public boolean add(E obj) {
if(obj == null){
throw new IllegalArgumentException("object cannot be null.");
}
if(this.currentSize == this.elements.length){
reAllocate();
}
E temp[];
temp = elements;
for(int i=0; i<= this.currentSize; i++){
//if(obj.compareTo(elements[i]) < 0){
//int target =i;
//elements[i+1] = temp[i];
//elements[target] = obj;
//break;
}
}
this.elements[this.currentSize++] = obj;
return true;
}
如果您告诉我“E”代表哪个类并显示其结构,我可以提出更好的方法。 –
看看如何使用'Arrays.binarySearch'来确定插入应该发生的元素[]中的确切索引,然后编辑类似于'java.util.ArrayList'内发生的数组。 – cambecc
E将是来自Class联系人的姓氏(字符串)。 –