我正在制作一个通用方法,它可以采用任何类型的列表并在该列表中找到最大值的位置,这是我制作的更大程序的一部分,我制作了一个迭代器,用于遍历列表。我快完成了,但我有两个问题: 1. 我无法在泛型方法中初始化迭代器。2. 无法从列表中获取第一个值。我不擅长解释,而是对代码中的问题区域进行了注释。任何帮助深表感谢!
通用方法:
public static <T> int max(List<T> list, Comparator<? super T> c)
{
if (list == null)
{
throw new NoSuchElementException();
}
int m = 0; // index max value
T maxvalue = list[0]; // max value (error: How do it get the value of the list here?)
int counter = 0;
Iterator<T> it = new DobbeltLenketListeIterator(); //( error: cannot be referenced from a static context)
while(it.hasNext())
{
counter++;
if (c.compare(it.next(), maxvalue) > 0)
{
maxvalue = it.next;
m = counter;
}
}
return m;
}
迭代器:
private class DoublelinkedlistIterator implements Iterator<T>
{
private Node<T> p;
private boolean removeOK;
private DoublelinkedlistIterator()
{
p = head;
removeOK = false;
}
public boolean hasNext()
{
if(p.next != null )
{
return true;
}
return false;
}
public T next()
{
if( hasNext() == false)
{
throw new NoSuchElementException();
}
Node<T> q = p;
p = p.next;
removeOK = true;
return q.value;
}
public void remove()
{
if(!removeOK) throw new IllegalStateException("illegal!");
removeOK = false;
Node<T> q = head;
if(head.next == p)
{
head = head.next;
if(p== null) tale = null;
}
else
{
Node<T> r = head;
while (r.next.next != p)
{
r = r.next;
}
q= r.next;
r.next = p;
if(p== null) tale = r;
}
q.value = null;
q.value = null;
}
}
public Iterator<T> iterator()
{
return new DoublelinkedlistIterator();
}
public Iterator<T> iterator(int index)
{
indexcontrol(index);
Iterator<T> it = new DoublelinkedlistIterator();
for (int i = 0; i < index && it.hasNext(); i++, it.next());
return it;
}