Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create divyasisss2 #2609

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions divyasisss2
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
// Java Program to Implement Behavioral>Iterator Pattern

// importing required package to
// implement Behavioral>Iterator Pattern
package com.demo.application;

// Importing required libraries
// Here Iterator Interface to
// use it to iterate over the elements
import java.util.Iterator;


// Class 1

// Car Class Implementing Iterable Interface so
// that we can implement the iterator method and
// add our own implementation

public class Car implements Iterable<String> {
private String[] cars;
private int index;

// Default Constructor
public Car() {
cars = new String[10];
index = 0;
}

// Method 1
// Adding method to add Cars
public void addCar(String car) {
if (index == cars.length) {
String[] largerCars = new String[cars.length + 5];
System.arraycopy(cars, 0, largerCars, 0, cars.length);
cars = largerCars;
largerCars = null;
}
cars[index] = car;
index++;
}

// Method 2
// Implementing the iterator method and
// adding your own implementation
@Override
public Iterator<String> iterator() {
Iterator<String> it = new Iterator<String>() {

private int currentIndex = 0;

// Method 3
// Finding whether during iteration if
// there is next element or not
@Override
public boolean hasNext() {
return currentIndex < cars.length && cars[currentIndex] != null;
}

// Method 4
// Going to grab each car element by one by one
// according to the index
@Override
public String next() {
return cars[currentIndex++];
}

// Method 5
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};

return it;
}

// Method 6
// Main driver method
public static void main(String[] args) {

// Instantiating Car object
Car cars = new Car();

// Adding cars to the Array
cars.addCar("Dodge");
cars.addCar("Ferrari");
cars.addCar("Sedan");

// Creating an Iterator and pointing the cursor
// to the index just before the first element in cars
Iterator<String> carIterator = cars.iterator();

// Checking whether the next element is available or not
while (carIterator.hasNext()) {
System.out.println(carIterator.next());
}
}
}