I have a task to implement a collection of elements in ascending order, along with methods of adding an element to the collection, printing all the elements in the collection and loading an element (along with removing it from the collection, I can assume that I'm always loading the smallest one).
I'm supposed to use Comparable<T>
interface.
Additionally, I need to implement a class hierarchy with the use of Comparable<T>
interface (for example, it can be a hierarchy of military ranks).
Here is my code:
public class Collection<T extends Comparable<T>> implements Iterable<T>
{
public LinkedList<T> collection;
public Collection()
{
collection = new LinkedList<>();
}
public void addToList(T new)
{
int i = 0;
while (collection .get(i).compareTo(new) < 0)
{
i++;
}
collection.add(i, new);
}
public T load() throws EmptyStackException
{
if (collection.size() == 0)
{
throw new EmptyStackException();
}
T first = collection.getFirst();
collection.removeFirst();
return first;
}
public void printElements()
{
for (T obj : collection)
{
System.out.println(obj);
}
}
@Override
public Iterator<T> iterator()
{
return this.collection.iterator();
}
}
public abstract class Soldier implements Comparable<Soldier>
{
public String Name;
public abstract double Rank();
public int compareTo(Soldier S)
{
if(S.Rank() == this.Rank())
{
return 0;
}
else if (S.Rank() < this.Rank())
{
return 1;
}
else return -1;
}
}
public class General extends Soldier
{
public double Rank()
{
return 4;
}
public General(String Name)
{
this.Name = Name;
}
}
public class Colonel extends Soldier
{
public double Rank()
{
return 3;
}
public Colonel(String Name)
{
this.Name = Name;
}
}
public class Corporal extends Soldier
{
public double Rank()
{
return 2;
}
public Corporal(String Name)
{
this.Name = Name;
}
}
public class Private extends Soldier
{
public double Ranga()
{
return 1;
}
public Private(String Name)
{
this.Name = Name;
}
}
When I tried to run some tests I got an error "Index out of bounds". What is actually happening here? I suspect that I can't add an element to my collection properly. Is this code correct?
The problem can be isolated here:
public LinkedList<T> collection;
public Collection()
{
collection = new LinkedList<>();
}
public void addToList(T new)
{
int i = 0;
while (collection.get(i).compareTo(new) < 0)
{
i++;
}
collection.add(i, new);
}
The first time you try to add an element, you pass zero to collection.get
. This attempts to get the first element (as List
s are zero-indexed) but there is no first element to get.
Additionally, 'new' is a keyword in Java and cannot be used as an identifier.