public class SeqList
时间: 2024-05-22 18:16:04 浏览: 96
{
private int[] data;
private int size;
// Constructor
public SeqList(int capacity)
{
data = new int[capacity];
size = 0;
}
// Getters
public int getSize()
{
return size;
}
public int getCapacity()
{
return data.length;
}
// Methods
public boolean isEmpty()
{
return size == 0;
}
public boolean isFull()
{
return size == data.length;
}
public void clear()
{
size = 0;
}
public void add(int index, int element)
{
if (index < 0 || index > size)
{
throw new IndexOutOfBoundsException("Index out of range: " + index);
}
if (isFull())
{
throw new IllegalStateException("List is full");
}
for (int i = size - 1; i >= index; i--)
{
data[i + 1] = data[i];
}
data[index] = element;
size++;
}
public void add(int element)
{
add(size, element);
}
public int remove(int index)
{
if (index < 0 || index >= size)
{
throw new IndexOutOfBoundsException("Index out of range: " + index);
}
int removed = data[index];
for (int i = index + 1; i < size; i++)
{
data[i - 1] = data[i];
}
size--;
return removed;
}
public int get(int index)
{
if (index < 0 || index >= size)
{
throw new IndexOutOfBoundsException("Index out of range: " + index);
}
return data[index];
}
public void set(int index, int element)
{
if (index < 0 || index >= size)
{
throw new IndexOutOfBoundsException("Index out of range: " + index);
}
data[index] = element;
}
public int indexOf(int element)
{
for (int i = 0; i < size; i++)
{
if (data[i] == element)
{
return i;
}
}
return -1;
}
public boolean contains(int element)
{
return indexOf(element) != -1;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < size; i++)
{
sb.append(data[i]);
if (i != size - 1)
{
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
}
阅读全文