Class Derived Iterator - java

What does it mean for an iterator to be derived from a class?
More specifically, I have two classes DNode and DoublyLinkedList. DoublyLinkedList uses DNode to construct the list and I'm using both to create a stack and queue. How do I write a method which returns a class derived iterator?
Here's what I have currently:
public Iterator <E> getCollectionIterator() {
Iterator <E> i = new Iterator <E>() {
private int currentIndex = 0;
#Override
public boolean hasNext() {
return (currentIndex < size && arrayList[currentIndex] != null);
}
#Override
public E next() {
if(hasNext()) {
return arrayList[currentIndex++];
} else
throw new NoSuchElementException("Next element does not exist.");
}
#Override
public void remove() {
throw new UnsupportedOperationException("Remove not supported");
}
};
return i;
}

Related

Implementer Iterator

I am currently trying to implement Iterator which receives a collection and a char and that yields the
Strings that starts with that char.
So I ended up with the following (working) code:
class A {
public static void main (String [] args) {
String [] arr = {"abcd","gr","gres","bvg","bb"};
class FirstCharIt implements Iterator<String> {
char c;
private Iterator<String> it;
public FirstCharIt (Collection<String> lst,char c) {
this.c = c;
this.it = lst.stream().filter(x->{
return (x.charAt(0)==this.c);
}).iterator();
}
#Override
public boolean hasNext() {
return it.hasNext();
}
#Override
public String next() {
return it.next();
}
public Iterator<String> get () {
return it;
}
}
FirstCharIt it1 = new FirstCharIt(Arrays.asList(arr),'b');
for (it1.get();it1.hasNext();) {
System.out.println(it1.next());
}
}
}
Although this code is working this is not actually implementing Iterator interface and I even can remove the 'implements Iterator' from my class headline.
And of course the method get wasn't there in more right implementation
So I would like to have some advice about what I did here,
thanks
Filter the input list at initialization, have that filtered collection and an index as fields of your iterator.
Have hasNext() check if the index has reached the end of the filtered collection, and next() increase the index and return the element it previously pointed at.
static class FirstCharIt implements Iterator<String> {
private int currentIndex;
private List<String> filtered;
public FirstCharIt (List<String> coll, char letter) {
this.filtered = coll.stream().filter(x->x.startsWith(""+letter)).collect(Collectors.toList());
this.currentIndex = 0;
}
#Override
public boolean hasNext() {
return currentIndex < filtered.size();
}
#Override
public String next() {
if (!hasNext()) { throw new NoSuchElementException(); }
return filtered.get(currentIndex++);
}
}
You can try it here.

compare an element of a list with the following in a recursively way

Hi,
Update: Thanks for all your suggestion
assuming that, this exercise it's like a rebus,
I have a list of numbers made with the concept of Cons and Nil,
List l = new Cons(**3**, new Cons(**2**,new Cons(**1**, new
Cons(**4**, new Cons(**1**, new Nil())))));
and I want to count how many of them are immediately followed by a lower number, recursively.
For example
[5,0,5,3].count() == 2, [5,5,0].count() == 1
The count() method is made by me (it cannot have any parameters), the rest is default, and I can't make and other method or use already defined one's like add(),size()...
The "NEXT" must have the next value after the current elem but I can't get a solution.
Any solutions are welcome.
abstract class List {
public abstract boolean empty();
public abstract int first();
public abstract int count();
}
class Cons extends List {
private int elem;
private List next;
public Cons(int elem, List next) {
this.elem = elem;
this.next = next;
}
public boolean empty(){
return false;
}
public int first(){
return elem;
}
#Override
public int count() {
if(elem>NEXT) {
return 1 + next.count();
}else {
return next.count();
}
}
```![enter image description here](https://i.stack.imgur.com/kWo0v.jpg)
The following code will create a recursive list with N elements with N value being defined by the size of the amount of elements found in the int array called elements in RecursiveList class. Call the startRecursion() method to create a recursive list with the defined elements and call count() to get the amount of elements in the array that are immediately followed by a lower number.
Main Class
This your application entry point:
public static void main(String[] args) {
int count = RecursiveList.startRecursion().count();
System.out.printf("List has %d recursive elements", count);
}
RecursiveList Class
abstract class RecursiveList {
protected static int index = -1;
protected static int[] elements = new int[]{ 5,2,1,4,3,2,6 };
public static RecursiveList startRecursion() {
return new Cons();
}
public abstract boolean empty();
public abstract int count();
public abstract Integer getElement();
public static int incIndex() {
return index += 1;
}
}
Cons Class
public class Cons extends RecursiveList {
private static int result;
private final Integer elem;
private final RecursiveList prev;
private final RecursiveList next;
private Cons(Cons parent) {
prev = parent;
elem = incIndex() < elements.length ? elements[index] : null;
System.out.printf("Creating new Cons with element %d(%d)%n", elem, index);
next = elem != null ? new Cons(this) : null;
}
Cons() {
this(null);
}
public boolean empty() {
return false;
}
#Override
public /*#Nullable*/ Integer getElement() {
return elem;
}
#Override
public int count() {
if (elem != null)
{
if (prev != null && elem < prev.getElement())
result += 1;
if (next != null) {
return next.count();
}
}
return result;
}
}
EDIT
Alright here is the answer you were actually looking for. This completely conforms to the limitations imposed on this exercise that you provided. The solution uses pure Java, neither the class nor any of it's method or field declarations were modified in any way and no such new elements were added. I've only added the implementation where the exercise said you should.
Main Class
public static void main(String[] args) {
List l = new Cons(3, new Cons(2,new Cons(1, new
Cons(4, new Cons(1, new Nil())))));
assert l.count() == 3;
l = new Cons(5, new Nil());
assert l.count() == 0;
l = new Cons(5, new Cons(5, new Cons(0, new Nil())));
assert l.count() == 1;
l = new Cons(5, new Cons(0, new Cons(5, new Cons(3, new Nil()))));
assert l.count() == 2;
System.out.println("All tests completed successfully!");
}
Cons Class
import java.util.NoSuchElementException;
public class Cons extends List {
private int elem;
private List next;
public Cons(int elem, List next) {
this.elem = elem;
this.next = next;
}
public boolean empty()
{ return false; }
public int first()
{ return elem; }
public int count()
{
try {
if (first() > next.first()) {
return 1 + next.count();
}
else return next.count();
}
catch (NoSuchElementException e) {
return 0;
}
}
}
Nil Class
import java.util.NoSuchElementException;
public class Nil extends List {
public boolean empty()
{ return true; }
public int first()
{ throw new NoSuchElementException(); }
public int count()
{
throw new IllegalAccessError();
}
}
public int NEXT(){
if(next!=null)
return next.first()
else
throw new Exception("No next element")
}

java iterator with index parameter

hi a normal iterator for a LinkedList would be the following, however, how do we build an iterator that returns an iterator starting at a specified index? How do we build:
public Iterator<E>iterator(int index)???
thanks!
normal Iterator:
public Iterator<E> iterator( )
{
return new ListIterator();
}
private class ListIterator implements Iterator<E>
{
private Node current;
public ListIterator()
{
current = head; // head in the enclosing list
}
public boolean hasNext()
{
return current != null;
}
public E next()
{
E ret = current.item;
current = current.next;
return ret;
}
public void remove() { /* omitted because optional */ }
}
Well you could just call the normal iterator() method, then call next() that many times:
public Iterator<E> iterator(int index) {
Iterator<E> iterator = iterator();
for (int i = 0; i < index && iterator.hasNext(); i++) {
iterator.next();
}
return iterator;
}
This is kick-off example how to implement such iterator, but it's advised also to create or extend appropriate interface and make this object implementing this interface for convention.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IterableObject {
private List<String> values = new ArrayList<String>();
public Iterator<String> getIterator(final int index) {
Iterator<String> it = new Iterator<String>() {
private int current = index;
#Override
public void remove() {
// TODO Auto-generated method stub
}
#Override
public String next() {
String value = values.get(current);
current++;
return value;
}
#Override
public boolean hasNext() {
if(values.size() > current){
return true;
}else{
return false;
}
}
};
return it;
}
}
UPDATE
According to comments I've written an Iterator for LinkedList
public Iterator<String> getIterator(final int index) {
Iterator<String> it = new Iterator<String>() {
private Object currentObject = null;
{
/*initialize block where we traverse linked list
that it will pointed to object at place index*/
System.out.println("initialize" + currentWord);
for(int i = 0; currentObject.next != null && i < index; i++, currentObject = currentObject.next)
;
}
#Override
public void remove() {
// TODO Auto-generated method stub
}
#Override
public String next() {
Object obj = currentObject.next;
currentObject = currentObject.next;
return obj;
}
#Override
public boolean hasNext() {
return currentObject.next != null;
}
};
return it;
}
Because Iterator is object of Anonymous class we can't use constructor but can initialise it in initialise block look at this answer: https://stackoverflow.com/a/362463/947111 We traverse it once at the beginning (sorry for C style) so it will point to currentObject. All remain code is self explained.

Creating an ArraySetIterator <E> Class

I'm creating an ArraySetIterator Class and having trouble with the next() method.
I have done some research but nothing seems to work for me. I'm sure its a simple piece of code but I can't seem to figure it out....
private class ArraySetIterator <E> implements Iterator <E> {
private ArraySet<E> set;
private int index = 0;
public ArraySetIterator(ArraySet<E> set) {
this.set = set;
}
public boolean hasNext() {
return (index + 1) < set.size();
}
public E next() {
???
}
public void remove() {
set.remove(index);
}
}
next() should increase the index and return the current element. I addition, it should throw NoSuchElementException if there are no more elements left to iterate over.
This works:
public E next() {
return set.get(index++);
}
You might also want to think about checking to see if hasNext() is true.
EDIT: Based on your comment, it sounds like your ArraySet is only implementing the Set interface. So you can't use .get(). I think you need do do something like this instead:
private class ArraySetIterator <E> implements Iterator <E> {
private E[] set;
private int index = 0;
public ArraySetIterator(ArraySet<E> set) {
this.set = (E[]) set.toArray();
}
public boolean hasNext() {
return (index + 1) < set.length;
}
public E next() {
if(hasNext) {
return set[index++];
} else {
throw new NoSuchElementException();
}
}
public void remove() {
throw new UnsupportedOperationException();
}
}

Incompatible Types Error in Java

I keep receiving an error that says that there are incompatible types. I copied this directly out of a book because we are supposed to make changes to the code to enhance the game of War. I have all of the other classes complete and compiled but this one is giving me fits. Here is the code:
public class ArrayStack<E> implements Stack<E> {
private E[] data;
private int size;
public ArrayStack() {
data = (E[])(new Object[1]);
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public Object pop() {
if (isEmpty()) {
throw new EmptyStructureException();
}
size--;
return data[size];
}
public Object peek() {
if (isEmpty()) {
throw new EmptyStructureException();
}
return data[size - 1];
}
protected boolean isFull() {
return size == data.length;
}
public void push(Object target) {
if (isFull()) {
stretch();
}
data[size] = target;
size++;
}
protected void stretch() {
E[] newData = (E[])(new Object[data.length * 2]);
for (int i = 0; i < data.length; i++) {
newData[i] = data[i];
}
data = newData;
}
}
The error is occurring in the push() method at the data[size] = target; line.
EDIT:::
I'm now receiving this error.
"type Stack does not take parameters
public class ArrayStack implements Stack"
The stack class is as follows.
public interface Stack<E> {
public boolean isEmpty();
public E peek();
public E pop();
public void push(E target);
}
Change Object to E as the push() method's parameter type.
public void push(E target) {
if (isFull()) {
stretch();
}
data[size] = target;
size++;
}
Likewise, you should also change the declare return type of pop() and peek() to E.
public E pop() {
if (isEmpty()) {
throw new EmptyStructureException();
}
size--;
return data[size];
}
public E peek() {
if (isEmpty()) {
throw new EmptyStructureException();
}
return data[size - 1];
}
Now your class is fully generic.
push method is not generic like the rest of the class, change it to:
public void push(E target) {
if (isFull()) {
stretch();
}
data[size] = target;
size++;
}
In any case the JDK ships with the class ArrayDeque which fulfill your requirements without being a piece o code pasted from a book.
ArrayDeque<YourObj> stack = new ArrayDeque<YourObj>();
stack.push(new YourObj());
YourObj head = stack.peek();
head = stack.pop();

Categories

Resources