我正在实现一种方法,该方法检查ArrayList中最大数连续相等元素的数目:
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这个实现有什么问题?
发布于 2016-02-10 09:26:01
但是,我得到的输出表明,它并不是真正地将当前元素与下一个元素进行比较。
实际上,它将在每一种情况下将一个项目与其本身进行比较。
毕竟,您从index = 0开始,在第一次迭代时使用array.get(index)和listIterator.next(),这两个迭代都将返回第一个元素。
一种更好的方法(IMO)是完全摆脱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)当然,现在不能进行计数,但是如果第一次对hasNext()的调用返回false (如果需要的话),则可以抛出一个异常,而不是返回0。
发布于 2016-02-10 09:25:48
E currentItem =array.get(指数); E nextItem = listIterator.next();
这两个语句都将在第一个迭代中返回0th元素,在下一个迭代中返回1st等等。最后,您将每个元素与自身进行比较,而不是以另一种方式进行比较。
发布于 2016-02-10 09:26:40
我想你在这里有个问题:
E currentItem = array.get(index);
E nextItem = listIterator.next();因为当while循环开始时,索引是0,迭代器指向第一个元素(使用索引0)。然后,next()移动您的迭代器,并将增量移动到inex。所以你把每一个元素和它自己进行比较。
希望这能有所帮助。
https://stackoverflow.com/questions/35311111
复制相似问题