2016-02-10 7 views
2

Я работаю над внедрением метода, который проверяет числа максимальное количество последовательных одинаковых элементов в ArrayList:Java ListIterator осветление

public class ArrayReader<E> { 

    public int getMaxConsecutiveEqualElements(ArrayList<E> array){ 

     if (array == null){ 
      throw new IllegalArgumentException("Array is null"); 
     } 
     if (array.size() == 0){ 
      throw new IllegalArgumentException("Array has 0 elements"); 
     } 

     int max = 1; 
     int currentMax = 0; 
     int index = 0; 
     ListIterator<E> listIterator = array.listIterator(0); 

     while (listIterator.hasNext()){ 
      E currentItem = array.get(index); 
      E nextItem = listIterator.next(); 

      System.out.println("Current item: " 
        + "index (" + listIterator.previousIndex() + ") " 
        + currentItem.toString() + " Next item: " 
        + "index (" + (listIterator.previousIndex() + 1) + ") " 
        + nextItem.toString()); 

      if (currentItem.equals(nextItem)){ 
       currentMax++; 
       if (currentMax > max){ 
        max = currentMax; 
       } 
      } else { 
       currentMax = 1; 
      } 

      index++; 
     } 

     return max; 
    } 

} 

public static void main(String[] args){ 

     ArrayList<Integer> array = new ArrayList<>(); 
     array.add(2); 
     array.add(2); 
     array.add(2); 
     array.add(5); 
     array.add(5); 
     array.add(5); 
     array.add(5); 

     ArrayReader<Integer> intArrayReader = new ArrayReader<>(); 
     System.out.println(intArrayReader.getMaxConsecutiveEqualElements(array)); 

    } 

Однако вывод я получаю показывает, что это на самом деле не сравнивая текущий элемент к следующему:

Current item: index (0) 2 Next item: index (1) 2 
Current item: index (1) 2 Next item: index (2) 2 
Current item: index (2) 2 Next item: index (3) 2 
Current item: index (3) 5 Next item: index (4) 5 
Current item: index (4) 5 Next item: index (5) 5 
Current item: index (5) 5 Next item: index (6) 5 
Current item: index (6) 5 Next item: index (7) 5 
7 

Что не так с этой реализацией?

+0

Там нет ничего плохого здесь. 'currentItem' всегда равен' nextItem' с вашим кодом. – Tunaki

ответ

1

Однако вывод я получаю показывает, что это на самом деле не сравнивая текущий элемент к следующему

В самом деле, он будет сравнивать один элемент с самим собой в каждом случае.

В конце концов, вы начинаете с index = 0, и на первой итерации вы используете array.get(index) и listIterator.next(), оба из которых вернут первый элемент.

Лучшим подходом (ИМО) было бы полностью избавиться от части index и даже удалить бит ListIterator. Просто используйте:

Iterator<E> iterator = array.iterator(); 
if (!iterator.hasNext()) { 
    return 0; 
} 
E current = iterator.next(); 
while (iterator.hasNext()) { 
    E next = iterator.next(); 
    // Do comparisons here 
    current = next; 
} 

Затем вы можете изменить метод гораздо более общий:

public int getMaxConsecutiveEqualElements(Iterable<E> sequence) 

Вы не можете взять отсчет сейчас, конечно, - но вы можете бросить исключение вместо того, чтобы вернуться 0, если первый вызов hasNext() возвращает false, если вы хотите.

1

E currentItem = array.get (index);

E nextItem = listIterator.next();

Оба эти утверждения вернет вам 0th элемент в первой итерации, 1st в следующем и так далее. Вы заканчиваете сравнение каждого элемента с самим собой, а не с другим.

1

Я полагаю, у вас есть проблема здесь:

 E currentItem = array.get(index); 
     E nextItem = listIterator.next(); 

Потому что, когда цикл начинается в то время как ваш индекс 0 ваши итератор указывает на первый элемент (с индексом 0). Затем next() перемещает ваш итератор и ваш приращение inex. Таким образом, вы сравниваете каждый элемент с самим собой.

Надеюсь, это поможет.

0

Проблема заключается здесь:

E currentItem = array.get(index); 
E nextItem = listIterator.next(); 

Переменная nextItem такая же, как CurrentItem каждый раз.

1

Вы всегда сравниваете один и тот же индекс с самим собой. Например, на первой итерации вашего цикла index будет 0 и listIterator.next() также вернет 0-й элемент вашего списка.

Вы можете попробовать что-то вроде этого (если вы не имеете нулевых значений в списке):

int max = 0; 
int currentMax = 0; 
E lastItem = null; 

for(E item : array) { 

    if(item.equals(lastItem)) { 
     // Count maximum up 
     currentMax++; 
     if(currentMax > max) { 
      max = currentMax; 
     } 
    else { 
     // Reset if consecutive sequence ends 
     currentMax = 0; 
    } 

    // Save item for next round 
    lastItem = item; 
} 
Смежные вопросы