Встроенный метод, который я построил для реализации List, никогда не возвращает true.Это почти как если бы он не сравнивал объект, который я ему передал, с объектами, уже имеющимися в списке.Мне интересно, если метод .equals, который я использую, может быть проблемой.Переменные класса: private T [] list и private int entry.
Я попытался привести к Object, надеясь, что более общий тип может быть проще для метода equals.Я даже пытался напрямую сравнивать объекты, используя == безрезультатно.
public class MyList<T> implements MyCollectionInterface<T>
{
private T[] list;
private int entries;
private static final int DEFAULT_CAPACITY = 25;
private static final int MAX_CAPACITY = 100000;
private boolean integrityOK;
//***************************************************************
public MyList()
{
this(DEFAULT_CAPACITY);
}
//********************************************************************
public MyList(int capacity)
{
integrityOK = false;
if(capacity < DEFAULT_CAPACITY)
{
capacity = DEFAULT_CAPACITY;
}
else
{
checkCapacity(capacity);
}
@SuppressWarnings("unchecked") // Suppress an un-checked cast warning
from the compiler
// cast is safe because the new array
contains null entries
T[] tempList = (T[])new Object[capacity];
list = tempList;
entries = 0;
integrityOK = true;
}
//**************************************************************************
/**
* Adds a new entry to this collection
* @param newItem The object to be added to the collection
* @return True if the addition is successful, or false if not.
*/
public boolean add(T newItem)
{
boolean result = false;
if(isArrayFull())
{
ensureCapacity();
}
if(newItem != null)
{
list[entries + 1] = newItem;
entries++;
result = true;
}
else
{
result = false;
}
return result;
}// End add
//*******************************************************************
public T remove()
{
checkIntegrity();
T result = null;
if(entries > 0)
{
result = list[entries];
list[entries] = null; // Setting this to null flags it for removal and prevents malicious code from accessing it
entries--;
}
return result;
}
//********************************************************************
/**
* Removes one occurrence of a given entry from this collection.
* @param anEntry The entry to be removed.
* @return True if the removal was successful, or false if not.
*/
public boolean remove(T anEntry)
{
checkIntegrity();
boolean result = false;
for(int i = 1; i <= entries; i++)
{
if(list[i].equals(anEntry))
{
list[i] = null;
removeGap(i);
entries--;
result = true;
}
}
return result;
} // End remove
//**********************************************************************
/**
* Removes all entries from this collection.
*/
public void clear()
{
while(!isEmpty())
{
remove();
}
}
//**********************************************************************
/**
* Gets the current number of entries in this collection.
*
* @return The integer number of entries currently in the collection.
*/
public int getCurrentSize()
{
return entries;
}
//***********************************************************************
/**
* Check to see if the collection is empty.
* @return True if the collection is empty, or false if not.
*/
public boolean isEmpty() {
return entries == 0;
} // End isEmpty
//**********************************************************************
/**
* Counts the number of times a given entry appears in this collection.
* @param anEntry The entry to be counted.
* @return The number of times anEntry appears in the collection.
*/
public int getFrequencyOf(T anEntry)
{
checkIntegrity();
int frequency = 0;
for(int index = 1; index < entries; index++)
{
if (anEntry.equals(list[index]))
{
frequency++;
}// End if
}// End for
return frequency;
}
//********************************************************************
/**
* Tests whether this collection contains a given entry.
* @param anEntry The entry to locate.
* @return True if the collection contains anEntry, or false if not.
*/
public boolean contains(T anEntry)
{
checkIntegrity();
boolean found = false;
for (int index = 1; index <= entries; index++)
{
T result = list[index];
if(anEntry == result)
{
found = true;
}
}
return found;
} // End contains
//***********************************************************************
/**
* Retrieves all entries that are in this collection.
* @return A newly allocated array of all the entries in the collection.
* Note: If the collection is empty, the returned array is empty.
*/
public Object[] toArray()
{
Object[] anArray = new Object[entries];
for (int index = 0; index <= anArray.length; index++)
{
anArray[index] = list[index + 1];
} // End for
return anArray;
} // End toArray
//************************************************************************
public T getEntry(int position)
{
if(position < 1 || position > entries)
{
throw new IndexOutOfBoundsException("Position is out of bounds for the
list.");
}
T entry = null;
entry = list[position];
return entry;
}
//*****************************************************************
private void checkIntegrity()
{
if(!integrityOK)
{
throw new SecurityException("List object is corrupt.");
}
}// End checkIntegrity
//********************************************************************
private boolean isArrayFull()
{
return entries >= list.length;
}
//************************************************************************
private void ensureCapacity()
{
int capacity = list.length;
if(entries >= capacity)
{
int newCapacity = 2 * capacity;
checkCapacity(newCapacity);
@SuppressWarnings("unchecked") // Suppress an un-checked cast warning from the compiler - cast is safe because the new array contains null entries
T[] tempList = (T[])new Object[newCapacity];
for(int i = 1; i <= entries; i++)
{
tempList[i] = list[i];
}
list = tempList;
}
}
//************************************************************************
private void checkCapacity(int capacity)
{
if(capacity >= MAX_CAPACITY)
{
throw new IllegalStateException("Attempted to create a list that exceeded max capacity.");
}
}
//************************************************************************
private void removeGap(int givenPosition)
{
int removedIndex = givenPosition;
for (int index = removedIndex; index < entries; index++)
{
list[index] = list[index + 1];
}
} // end removeGap
//***********************************************************************
private void makeRoom(int givenPosition)
{
int newIndex = givenPosition;
int lastIndex = entries;
for (int index = lastIndex; index >= newIndex; index--)
{
list[index + 1] = list[index];
}
} //end makeRoom
} // End class
Метод должен возвращать true, если anEntry присутствует в списке, но никогда не возвращает.Всегда возвращает false.