I'm trying to create an iterator class that completes what I thought would be two simple methods but I am having issues I suppose creating the iterator. The line where I create the iterator is giving me a compile error saying "Iterator is abstract; cannot be instantiated". I am not too sure what that means, obviously I did something wrong though. Also I put the purpose of the methods above them, if you see anything wrong with them let me know. Thanks for any input!
import java.util.Iterator;
private class OrderedListIterator{
Iterator<E> it = new Iterator<E>();
//return true if iterator has more items
public boolean hasNext(){
boolean found = false;
if(it.hasNext == true)
found = true;
return found;
return found;
}
//return next item in the iterator
public E getNext(){
if(it.hasNext != false)
return it.next;
}
//prints out message
public void remove(){
System.out.println("Operation not supported");
}
}
The reason you are getting this error is because an iterator is an interface.
In the Java programming language, an interface is a reference type,
similar to a class, that can contain only constants, method
signatures, default methods, static methods, and nested types. Method
bodies exist only for default methods and static methods. Interfaces
cannot be instantiated—they can only be implemented by classes or
extended by other interfaces. Extension is discussed later in this
lesson.
From the Java docs https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html
An interface contains the definition of the methods, not the implementation and is why you can't create or call interfaces or it's methods. The iterator interface has two methods; hasNext() and next(). Your code looks like you intend to implement the iterator interface.
private class OrderedListIterator implements Iterator<E>
In your hasNext and next methods, you need to iterate over your OrderedList depending on how you have implemented it.
Here is an example of an iterator for an ArrayList which I have previously created.
private class ArrayIterator implements Iterator<E> {
private int arrayIndex = 0;
/**
* Checks if the set has a next value.
*
* #return true if there is a next value, else false
*/
public boolean hasNext() {
//Checks that the index is within the size of the ArrayList
return arrayIndex < size;
}
/**
* Gets the next value in the iteration.
*
* #return
* The next value in the list
* #throws NoSuchElementException
* if there is no next element in the list
*/
public E next() throws NoSuchElementException {
if (arrayIndex == size) {
throw new NoSuchElementException();
}
//Checks the ArrayList's data at the current index
return data[arrayIndex++];
}
}
Your private class is able to access the fields from it's surrounding class. In my example, the iterator stores an index (like an internal cursor) in the array and checks the ArrayList's data at the current index. Each time the next method is called, the index is increased for the next time.
If your OrderedList class is like a LinkedList and has nodes, you would save a reference to the node and each time the next method is called you would return the node, then change the cursor to the next node.
Related
Need help defining these methods, I am not familiar using Type T.
Define the following two methods in the LinkedList class:
1) The searchItem method takes an item to be search of type T in the list and if it is found then returns the position in the list, otherwise return -1
2) The removeItem method takes as argument an item to be removed of type T and returns true if the item is successfully removed, otherwise returns false.
This sounds suspiciously like homework.
When you create a generic class in java you just need the class to have the on it.
public class LinkedList<T>
The T can be any letter you want it to be. It does not matter what you choose. Then when you create an instance of that class you will give it type t.
LinkedList<int> mylist = new LinkedList<int>();
This will create an instance of the linked list where everything that references T will be replaced with int.
So your methods just need to use type T.
public class LinkedList<T>
{
public int Search(T toSearch)
{
//search your nodes
return -1;
}
public boolean Remove(T toRemove)
{
//find item and remove if you can, return true
return false;
}
}
Just as a final note, returning a boolean for success is BAD. It is an exceptional case if the user tries to remove something that isn't in the list, and should throw an exception. Otherwise it does not need to return anything.
I'm currently creating a class called ArraySet that implements the Set interface. I'm supposed to create an iterator method that returns the values in natural order, where the time complexities are iterator(): O(1); hasNext(): O(1); next(): O(1); required space: O(1). The method is supposed to return an Iterator that does this. I'm confused by the way this method works and what is exactly wanted from me. Because it's a method I shouldn't be able to create hasNext(), or next() methods inside of it, and what Iterator am I trying to return? I tried just returning an Iterator but it's abstract and cannot be instantiated. I can understand making a new iterator class, but am having trouble understanding how this works in method form. Basically, what the method looks like at the moment is this, but like I've said I don't know what to even put inside of it. Also, if it helps there are two fields in the ArraySet class, int size (the number of elements in the Array), and T[] elements (the array where the elements are stored, strictly in natural order though I'm not even sure how to enforce natural order)
public Iterator<T> iterator() {
return null;
}
Because it's a method I shouldn't be able to create hasNext(), or next() methods inside of it, and what Iterator am I trying to return?
No, methods cannot define other methods in Java. Are you perhaps thinking of defining an anonymous subclass of Iterator? That could work.
You need to create a concrete Iterator implementation. The iterator() method in your class will then instantiate and return a new instance of this implementation.
For clarity, here's what the skeleton of the thing might look like. It's up to you to implement the hasNext() and next() methods!
public class ArraySet<T> implements Iterable<T> {
// snip...
#Override
public Iterator<T> iterator() {
return new MyIterator();
}
private class MyIterator implements Iterator<T> {
#Override
public boolean hasNext() {
// your logic here
}
#Override
public T next() {
// your logic here
}
}
}
This case is perfect for an anonymous class.
Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
#Override
public Iterator<T> iterator() {
return new Iterator<T>() {
#Override
public boolean hasNext() {
// ...
}
#Override
public T next() {
//..
}
#Override
public void remove() {
//..
}
};
}
On the other hand, by natural order they mean that the elements of your structure must implement Comparable, and given the O(1) requeriments, the internal array holding the data should be already ordered according this natural order. A more flexible approach (used in standard java collections) is don't require the elements to be comparable, and instead support an optional comparator to be passed in the constructor.
As an additional note: Make your iterator a fail fast iterator, i.e, aware of concurrent modifications using counters for each modification operation, that will give you some points.
The idea is use a counter in the your ArraySet instance to count how many writing operations has been made (adding, removing). Then, when you create the iterator you record the current value of the counter (inside the iterator instance, or as a final variable in the iterator() method), and each time a method of the iterator instance is invoked you validate that the current value of the counter of the data structure is the same as the one recorded, meaning that not modification has been performed during the life of the iterator. Otherwise a ConcurrentModificationException is thrown.
Take a look at the source of some standard implementations for good examples.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I'm trying to implement linked Lists.
I therefore have this first class, called List, which represents one element
package list;
/**
* Linked list with int values.
*
* The empty list is represented by a null reference.
*/
public class List {
public int value;
public List next;
/**
* Creates a new list
*
* #param value value of the head of the list
* #param next reference to rest of the list; may be null
*/
public List(int value, List next)
{
this.value = value;
this.next = next;
}
}
and the linked list class itself which contains the following method
public static int size(List list)
{
if(list==null) return 0;
else return size(list.next)+1;
}
so far everything works. But if I try
public static int size(List list)
{
if(list.next==null) return 1;
else return size(list.next)+1;
}
i get a NullPointerException...
I have no Idea why this shouldn't work since list.next should a one point be a reference to the null pointer and end the recursion.
Therefore size(null.next) should never be called.
I apologise for the bad english and am grateful for any help
Your original size method handles null argument fine.
The second version does not.
The second version would only give NPE if you call List.size(null), for all non-null inputs, it should behave absolutely similarly.
Therefore, just add if (list == null) return 0; to your second version.
I really suggest that you declare size() a as member method:
public int size() {
return next == null ? 1 : next.size() + 1;
}
so you can call : new List(1, null).size();
That is because you call List.size(null). In the first version you checl for list==null, in the second you don't.
The answer was inspired by a previous comment.
It is actually possible to do this
List list = null;
LinkedList.size(list);
and therefore if the list is uninitialised null.next can be called.
In other words: my list has to have at least two elements (firstelement and null)!
So my program has a need of a type of circular ArrayList.
Only circular thing about it has to be the get(int index) method, this is the original:
/**
* Returns the element at the specified position in this list.
*
* #param index index of the element to return
* #return the element at the specified position in this list
* #throws IndexOutOfBoundsException {#inheritDoc}
*/
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
If index is -1 it should get the element with index ArrayList.size()-1 and if index is ArrayList.size(), it should get the element with index 0.
Simplest way of achieveing this which came to my mind is simply extending ArrayList from the java.util package and just overriding the get(int index) so it does not throw IndexOutOfBoundsException for the two indexes above, but change them to what I want. It would throw IndexOutOfBoundsException for any other index that is out of bounds.
However, since elementData(index) access a
private transient Object[] elementData;
I cannot make it work, because my class doesn't see it since it's private.
Also, I don't want to use any external libraries for this, simply because I think there are none that suit my needs, since I don't want a real circularArray, but only a part of it's functionality, rest of it being of the regular ArrayList.
So I have two questions:
How can I make this work? Is there a way to do it without copying the whole ArrayList class along with AbstractCollection, Collection and Iterable into my program? That seems like bad design even to me.
If I can somehow make it work, is there anything else I should watch for? If I make the changes described above, would that change the behaviour of the class only the way I want it to, or could there be any other undesired behaviour changes?
EDIT:
Thanks for the answer, here's what I've done:
import java.util.ArrayList;
public class CircularArrayList<E> extends ArrayList<E>
{
private static final long serialVersionUID = 1L;
public E get(int index)
{
if (index == -1)
{
index = size()-1;
}
else if (index == size())
{
index = 0;
}
return super.get(index);
}
}
It will wrap around the ArrayList, but only by one. I want it to throw an exception if I try to access any other element but the first and the last with anything except their regular ArrayList indexes.
You can extend the ArrayList class to change the functionality of the get method, without the need to access the elementData field:
public class CircularList<E> extends ArrayList<E> {
#Override
public E get(int index) {
return super.get(index % size());
}
}
The super.get method will still perform the range checks (but those will never fail).
You should be aware that doing this can give the ArrayList unstable indices. If the size of the list changes, then all indices outside of the normal range will change. For instance, if you have a list ['a','b','c','d','e'], then get(7) will return c. If you then do add('f'), then get(7) will suddenly return b, because get will now be working modulo 6 instead of modulo 5.
Can't you derive from ArrayList and override the the get(int index) method along those lines:
#Override
public E get(int index)
{
if(index < 0)
index = index + size();
return super.get(index);
}
What am I missing?
Note that this implementation would not fold arbitrary indices into your valid index range but only allow you to properly address your list from both the left and right sides (with positive and negative indices respectively, a bit like in Python).
What you described is basically getting the modulus of the index you want, and accessing that element in a list.
You could do the following with composition over inheritance:
Create a wrapper class for the interface List<T>, let's call it ListWrapper now
add a constructor accepting instance of List
let the List instance be protected, and name it to wrapped
Extend the wrapper class
Why do all this crap? This is implementation agnostic. One day, you might want to use this convenience on another implementation. Then you'll have to duplicate code, and hell begins. If you need a 3rd implementation too, and then add just one tiny bit of new functionality, you are doomed.
With a wrapper class in between:
you can have all classes implementing the List interface to have your own functinality
you'll be able to change the wrapper class in one place
you'll be able to add new functionality in one place.
Remember, we are writing programs that will have to be maintainable!
Wrapper class
public abstract class ListWrapper<T> implements List<T> {
protected final List<T> wrapped;
public ListWrapper(List<T> wrapped) {
this.wrapped = wrapped;
}
public T get(int index) {
return wrapped.get(index);
}
//omitting the other wrapper methods, for sake of brevity.
//Note: you still have to add them.
// Eclipse: Source menu, Generate Delegate methods does the trick nicely
}
Now the real new class
public class ModList<T> extends ListWrapper<T> {
public ModList(List<T> list) {
super(list);
}
#Override
public T get(int index) {
int listSize = wrapped.size();
int indexToGet = index % listSize;
//this might happen to be negative
indexToGet = (indexToGet < 0) ? indexToGet+listSize : indexToGet;
return wrapped.get(indexToGet);
}
}
BEWARE
this however is not safe for multithreaded environments!
be careful about all the instances of the original list - if you mutate that, the ModList instance will mutate too
The chosen answer doesn't handle the case where the index is a negative number with a very large magnitude and the size of the list is small i.e.
Size => 10
Index => -1000000
Here is an implementation that should handle all sizes and indexes
import java.util.ArrayList;
import java.util.Collection;
/**
* A list the loops round to the first element when {#link CircularList#get(int)} is called with an
* index that is greater than the max index of the list and vice versa.
*
* #author Stuart Clark
*/
public class CircularList<E> extends ArrayList<E> {
public CircularList() {
super();
}
public CircularList(int initialCapacity) {
super(initialCapacity);
}
public CircularList(Collection<? extends E> c) {
super(c);
}
#Override
public E get(int index) {
if (isEmpty()) {
throw new IndexOutOfBoundsException("The list is empty");
}
while (index < 0) {
index = size() + index;
}
return super.get(index % size());
}
}
Does anyone know this AbstractList extension : com.sun.appserv.management.util.misc.CircularList<T>. Take a look at it. It's GlassFish java.net community solution. It should be powerful because it's used in Thread Scheduling inside GlassFish Container.
The student at the top of the stack is Gullion,Hailey
Student Mcglothlen,Shizue is removed from the stack
Here are all the elements of the Stack using an Iterator
--------------------------------------------------------
Stack$Node#3012db7c
Stack$Node#2607c28c
Stack$Node#477588d5
Stack$Node#756a7c99
Stack$Node#221a5d08
Stack$Node#70d1c9b5
Stack$Node#5d11c3f0
Stack$Node#3956f14c
Stack$Node#7afbd1fc
null
Here are all the elements in the Stack
--------------------------------------
Putney,John
Larkey,Ismael
Winkler,Isiah
Aceto,Liana
Hamill,Crissy
Caraway,Elmira
Gullion,Hailey
Rodrigez,Jonie
Madruga,Terrell
Williams,Diego
The first list of elements of the Stack using an Iterator apparently is not working. I do not know why. Here is my code for Iterator in my Stack class:
public Iterator<Student> iterator() { return new ListIterator(); }
// an iterator, doesn't implement remove() since it's optional
private class ListIterator implements Iterator<Student> {
private Node<Student> current = top;
public boolean hasNext() {
return current != null;
}
public void remove() {
throw new UnsupportedOperationException();
#SuppressWarnings("unchecked")
public Student next() {
if (!hasNext()) throw new NoSuchElementException();
current = current.next;
return (Student)current;
}
}
Here is the code in my Driver class that is where there seems to be a problem:
System.out.println("\nHere are all the elements of the Stack using an Iterator");
System.out.println("--------------------------------------------------------");
Iterator <Student> iter = myStack.iterator();
while (iter.hasNext() )
System.out.println(iter.next() );
HERE IS ALL OF THE CLASSES:
Stack: http://pastebin.com/2HVLVHuM
Queue class: http://pastebin.com/3q537kHW
Student class: http://pastebin.com/UnBB7kPA
Driver class: http://pastebin.com/yeA34MNd
I CAN ONLY WRITE CODE IN THE STACK CLASS. The point of this was to Implement a stack using queues. Hope this helps
You need to add a toString() method in your Student class. The Iterator is working correctly, but the System.out.println() doesn't know how to display the Student.
Add something to the Student class like this...
public String toString(){
return name;
}
So that when you call System.out.println(), it can output a real value. When you call System.out.println(Object), it always tries to output the toString() value. If this method isn't defined, it will output the java ID of the object, which is what you're seeing.
current in your Stack iterator is defined as Node<Student>. You return current from your next() method using a cast.
So, next() returns a Node<Student> (type-cast to Student), instead of an actual Student. Since Node presumably doesn't have a toString method, you get the default output (Stack$Node#<addr>).
To fix, return something like current.item from next() instead (assuming that the item stored in the Node is called item).
First of all, see nneonneo 's answer for the incorrect cast in your next() method.
Secondly, your Iterator implementation is incorrect.
The next() function in your iterator returns the element current after setting it to current.next .
After calling next() on the last element of your iteration, hasNext() should return false. But it doesn't, because current still points to the element you just returned. So you will call next() again. And in this method, current = current.next will set current to null, and then return it. Which should not happen, since hasNext was true, right?
For the same reason, the fist elemtent of your stack is missing: You set current to the top element of your stack, but before outputting anything, you already switch to current = current.next. You should do that after doing the output.
The first list of elements of the Stack using an Iterator apparently is not working. I do not know why.
Because your iterator is returning a Node<Student> instead of a student. The problem is at:
return (Student)current;
You probably tried to do this, but got an Incompatible Type error:
return current;
So you tried to fix by casting. The problem is that a node is not a student. A node contains a student. You need to return the student that the node contains.
Try this:
return current.data;
No casting is required because the compiler knows that the "data" member of node is a Student, since you declared current of type Node<Student>. This will fix the problem where your student prints out incorrectly. However as pointed out by #Konstantin, your iterator is still broken. You need to save the value of current in a temporary variable, move current, then return the temporary variable. Here is one possible implementation:
public Student next() {
if (current == null) throw new NoSuchElementException();
Node<Student> result = current;
current = current.next;
return result.data;
}
[epilogue]
You really need to review the generics tutorial. It's not clear from the code you pasted in above but it's obvious in the paste-bin code that you are using Student as a type parameter. That is very non-standard and confusing. The convention is to use a capital letter - typically T. You should have declared stack like below. Everywhere you use Student, replace it with T.
public class Stack <T> implements Iterable<T>{ // good
instead of
public class Stack <Student> implements Iterable<Student>{ // bad
T means some type to be decided later and you can use Stack with any kind of object. Only when you actually create a stack to you use Student (or whatever)
public static void main(String [] args)
{
Stack<Student> x = new Stack<Student>();