Im making a generic method that can take any type of list and find the position of the max value in that list, this is part of a bigger program I have made and I have made a iterator that I use to run through the list. Im nearly finished but Im having two problems: 1. I cant initialize the iterator inside the generic method. 2. Cant get the first value from the list. Im not good at explaining, instead I commented the problem areas in the code. Any help is much appreciated!
The generic method:
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;
}
The iterator:
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;
}
This was a hard one but I got some help, the answer is: Iterator it = list.iterator();
T maxvalue = it.next();
Thank you both I appreciated your answers!