【发布时间】:2018-04-04 14:02:39
【问题描述】:
我的任务是实现一个按升序排列的元素集合,以及向集合中添加元素、打印集合中的所有元素和加载元素的方法(以及从集合中删除它,我可以假设我总是加载最小的)。
我应该使用Comparable<T> 接口。
另外,我需要使用Comparable<T>接口实现一个类层次结构(例如,它可以是一个军衔层次结构)。
这是我的代码:
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;
}
}
当我尝试运行一些测试时,我收到一个错误“索引超出范围”。这里实际发生了什么?我怀疑我无法正确地将元素添加到我的收藏中。这段代码正确吗?
【问题讨论】:
-
已经有一个名为
Collection的接口。我强烈建议您将您的更改为,例如,MyCollection,以避免名称冲突和导致不可避免的头痛。 -
kolekcja中的addToList定义在哪里?
标签: java collections interface comparable