[英]checking if an object is in a list before adding java
好的,我的add方法在添加新对象之前如何实现检查数组列表中是否存在对象时遇到问题。
我也想创建一个remove方法,但是每次尝试使用它时,都会出现空指针异常。
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()
请澄清。 您是否要检查两个单独创建的对象的内容是否相同? 还是要检查您之前是否添加了该对象?
所有对象都有一个.equals()方法,该方法检查两个引用是否为同一对象。
扩展Roey:
private boolean contains(Contact contact) {
for (int i = 0; i < contacts.length; i++) {
if (contacts[i].equals(contact)) {
return true;
}
}
return false;
}
在您的add方法中,调用contains方法:
if contains(contact)
return true
else
add object
至于remove方法,也可以使用contains方法。 通用伪代码:
if contains(contact)
shift all elements above contact down one slot
decrement size
return true
else
return true
如果要比较对象,建议您提供一个属性进行比较,否则,如果存在的对象与您要添加的当前对象之间存在一些差异,则最终将再次插入该对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.