Created
October 26, 2021 08:52
-
-
Save rchatley/21cb218d521d4f9a634a9caecc381f0c to your computer and use it in GitHub Desktop.
IterableAndCollection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.iteratrlearning.collections.examples._1_what_are_collections; | |
import java.util.AbstractCollection; | |
import java.util.Collection; | |
import java.util.Iterator; | |
public class CollectionExamples { | |
public static void main(String[] args) { | |
System.out.println("Square Number Sequence (Iterable)"); | |
System.out.println("******************************************"); | |
Iterable<Integer> sequence = new SquareNumbersSequence(); | |
for (Integer num : sequence) { | |
System.out.println(num); | |
} | |
System.out.println("\n\nSingleton Collection"); | |
System.out.println("******************************************"); | |
Collection<String> collection = new SingletonCollection<>(); | |
System.out.println(collection); | |
collection.add("first"); | |
System.out.println(collection); | |
collection.add("second"); | |
System.out.println(collection); | |
} | |
private static class SingletonCollection<T> extends AbstractCollection<T> { | |
private T elem; | |
@Override | |
public boolean add(T t) { | |
if (isEmpty()) { | |
elem = t; | |
return true; | |
} | |
return false; | |
} | |
@Override | |
public Iterator<T> iterator() { | |
return new SingleIterator(); | |
} | |
@Override | |
public int size() { | |
if (elem == null) { | |
return 0; | |
} else { | |
return 1; | |
} | |
} | |
private class SingleIterator implements Iterator<T> { | |
private int index; | |
@Override | |
public boolean hasNext() { | |
return !isEmpty() && index == 0; | |
} | |
@Override | |
public T next() { | |
index++; | |
return elem; | |
} | |
} | |
} | |
private static class SquareNumbersSequence implements Iterable<Integer> { | |
@Override | |
public Iterator<Integer> iterator() { | |
return new TermIterator(); | |
} | |
private class TermIterator implements Iterator<Integer> { | |
private int curr = 0; | |
@Override | |
public boolean hasNext() { | |
return curr < 100; | |
} | |
@Override | |
public Integer next() { | |
curr++; | |
return curr * curr; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment