好吧,我的 add 方法遇到了问题,如何在添加新对象之前检查对象是否已在数组列表中。
我还想创建一个删除方法,但每次我尝试使用它时都会遇到空指针异常。
import java.util.*;
public class ContactsArrayList extends AbstractList{
private Contact[] contacts;
private int size;
public ContactsArrayList(){
//initializes contactArray with a capacity of 1
contacts = new Contact[1];
size = 0;
}
public ContactsArrayList(int capacity){
if(capacity < 0){
try {
throw new Exception("Capacity: must be greater than zero.");
} catch (Exception e) {
e.printStackTrace();
}
}
contacts = new Contact[capacity];
size = 0;
}
public int size(){
//returns size of list
return size;
}
public boolean isEmpty(){
return size == 0;
}
private void listRangeCheck(int index){
//checks if index is within range as built in debugging method
if(index >= size || index < 0){
throw new IndexOutOfBoundsException("Index: " + index + " is not within the list.");
}
}
public Contact get(int index){
//returns index at Contact at specified index
listRangeCheck(index);
return contacts[index];
}
public void capacityCheck(int minCapacity){
//checks current capacity if capacity is less than required,
// array copies its current values over to an array double the size
int oldCapacity = contacts.length;
if(minCapacity > oldCapacity){
int newCapacity = (oldCapacity * 2);
if(newCapacity < minCapacity)
newCapacity = minCapacity;
contacts = Arrays.copyOf(contacts, newCapacity);
}
}
public boolean add(Contact contact){
//appends the specified element to the end
capacityCheck(size + 1);
contacts[size++] = contact;
return true;
}
public int capacity(){
//returns ContactArray size
return contacts.length;
}
public void sort() {
//sorts the specified contact array list
List<Contact> c_list = new ArrayList();
c_list = Arrays.asList(contacts);
Collections.reverse(c_list);
c_list.toArray(contacts);
}
}
最佳答案
一如既往的简单:
private boolean contains(Contact contact){
for (int i=0; i<contacts.length; i++){
if (<condition to know if the 'contact' object exists>) return true;
}
return false;
}
但是如果您考虑使用ArrayList<Contact>()
你可以简单地使用它的 contains()
关于java - 添加 java 之前检查对象是否在列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32771281/