Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Modify the body of the toString method so that it uses the for-each iterator idiom instead. How do I fix this code? import java.util.ArrayList; import

Modify the body of the toString method so that it uses the for-each iterator idiom instead.

How do I fix this code?

import java.util.ArrayList; import java.util.Iterator; import java.util.List;

/** * IteratorError.java * Illustrates a common error when using Iterators. */ public class IteratorError {

/** * Identify and eliminate the errors regarding the use * of the iterator itr in the following method. */ public static int search(List list, T target) { int i = 0; Iterator itr = list.iterator(); while ((itr.hasNext()) && (!itr.next().equals(target))) { i++; itr.next(); } if (itr.hasNext()) { return i; } else { return -1; } }

/** Drives execution. */ public static void main(String[] args) { List ilist = new ArrayList(); ilist.add(2); ilist.add(4); ilist.add(6); ilist.add(8); ilist.add(10);

int loc = IteratorError.search(ilist, 8); System.out.println(loc); loc = IteratorError.search(ilist, 5); System.out.println(loc); }

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Data Mining Concepts And Techniques

Authors: Jiawei Han, Micheline Kamber, Jian Pei

3rd Edition

0123814790, 9780123814791

More Books

Students also viewed these Databases questions

Question

=+2 How does the preparation and support for each type of IE vary?

Answered: 1 week ago