PowersOf2Iterable

From CSE231 Wiki
Revision as of 18:56, 31 January 2023 by D.Linus (talk | contribs) (Adding note on how to create anonymous inner class)
Jump to navigation Jump to search

Motivation

  • Gain experience with implementing interfaces.
  • Build a utility which will come in handy later in the semester (for example, the Scan exercise).


Investigate

anonymous classes

interface Iterable<T>

interface Iterator<T>

Mistakes To Avoid

Attention niels epting.svg Warning: Do NOT Parallelize
Attention niels epting.svg Warning: Do NOT confuse Iterable<T> from Iterator<T>

How To Use

for(int v : new PowersOfTwoLessThan(71)) {
    System.out.println(v);
}

should produce the output:

1
2
4
8
16
32
64

Code to Implement

It is important to consider what state each class should encapsulate. The class PowersOfTwoLessThan, which is Iterable, should be have need to store little (if anything) beyond the maxExclusive passed in to its constructor. Further, PowersOfTwoLessThan should be immutable. There is no need to change any of the data during its lifetime.

The Iterator<Integer> instances created whenever one invokes the iterator() method? Now, the data for those instances are going to need to mutate.

One should NOT need to create a List to support this class. A single private final int instance variable is all you need for PowersOfTwoLessThan and a single (mutable) int instance variable is all you need for its Iterator.

class: PowersOfTwoLessThan.java Java.png
methods: constructor
iterator
package: iteration.powersoftwo.exercise
source folder: student/src/main/java

constructor

constructor: public PowersOfTwoLessThan(int maxExclusive)

iterator

method: public Iterator<Integer> iterator() Sequential.svg (sequential implementation only)

You can create an anonymous inner class or a named class if you prefer.

Note: if you type the following, IntelliJ will offer you to "Implement methods" necessary to create an anonymous inner class

return new Iterator<>() {
      // Implement/Override necessary methods
}

Testing Your Solution

Correctness

class: _PowersOfTwoTestSuite.java Junit.png
package: iteration.powersoftwo.exercise
source folder: testing/src/test/java

Pledge, Acknowledgments, Citations

file: studio-powers-of-two-iterable-pledge-acknowledgments-citations.txt

More info about the Honor Pledge