I wrote these codes in Idea. The IDE throws "can't resolve method get in Deque.java" when I finished Palindrome.java. How come? I actually did that in the Deque.java. Although in the LinkedListDeque inherited the get() method from the origin LinkList.
I found another solution by changing
Deque stringDeque = wordToDeque(word);
to
LinkListDeque stringDeque = (LinkListDeque) wordToDeque(word);
But I am still curious about how cannot find get in Deque.
class diagram here
Deque interface
/** Create an interface in a new file named Deque.
* java that contains all of the methods that appear in both ArrayDeque and LinkedListDeque.
* #param <Item>
*/
public interface Deque<Item> {
int size = 0;
/** Adds an item of type T to the front of the deque. */
void addFirst(Item item);
/** Adds an item of type T to the back of the deque. */
void addLast(Item item);
/** Returns true if deque is empty, false otherwise. */
default boolean isEmpty() {
return size == 0;
};
/** Prints the items in the deque from first to last,
* separated by a space. Once all the items have been printed, print out a new line. */
void printDeque();
/** Removes and returns the item at the front of the deque. If no such item exists, returns null. */
Item removeFirst();
/** Removes and returns the item at the back of the deque. If no such item exists, returns null. */
Item removeLast();
/** Gets the item at the given index, where 0 is the front, 1 is the next item, and so forth.
* If no such item exists, returns null. Must not alter the deque! */
Item get(int index);
}
class LinkedLinkDeque.java
import java.util.LinkedList;
import java.util.NoSuchElementException;
/**
* Isn't this solution kinda... cheating? Yes.
*/
public class LinkedListDeque<Item> extends LinkedList<Item> implements Deque<Item> {
#Override
public void printDeque() {
System.out.println("dummy");
}
public Item getRecursive(int i) {
return get(i);
}
#Override
public Item removeFirst() {
try {
return super.removeFirst();
} catch (NoSuchElementException e) {
return null;
}
}
#Override
public Item removeLast() {
try {
return super.removeLast();
} catch (NoSuchElementException e) {
return null;
}
}
}
Palindrome.java
import java.util.Deque;
import java.util.LinkedList;
public class Palindrome {
/** Given a String, wordToDeque should return a Deque
* where the characters appear in the same order as in the String.
* #param word
*/
public Deque<Character> wordToDeque(String word) {
Deque<Character> stringDeque = new LinkedListDeque<>();
for (String s : word.split("")) {
stringDeque.addLast(s.charAt(0));
}
return stringDeque;
}
/** Return true if the given word is a palindrome, and false otherwise. */
public boolean isPalindrome(String word) {
if (word.length() == 0 || word.length() == 1) {
return true;
}
Deque stringDeque = wordToDeque(word);
int index = word.length() / 2;
for (int i = 0; i < index; i += 1) {
if (stringDeque.get(i) != stringDeque.get(word.length() - i - 1)) { return false; }
}
return true;
}
}
You have your own Deque interface but you are also working with the java.util.Deque interface. This can result in problems as the interface Deque is defined twice in different namespaces. Specially in your Palindrome.java file you are using the java.util.Deque interface because of the import java.util.Deque line at the top and NOT your Deque interface as you might expect.
Because of that you get the error message that the get(int) method is missing. That is correct, the java.util.Deque method does not define a get(int) method (but the java.util.List interface does).
Do not name classes with names which already exists in java. As you see that can result in naming conflict/issues.
Related
I need help to understand how the testing should go through. I should implement the test method in stacktest.java ( have already done that). Then extend Stacktest with LinkedlistTest ( i have already done that). Then add super.setUp() as the first line in LinkedListTest.setUp (I have done that). But the one overriden method is getIntegerStack that I implement in the LinkedListTest, but then i Get a error " 'getIntegerStack()' in 'LinkedListTest' clashes with 'getIntegerStack()' in 'StackTest'; attempting to use incompatible return type " I dont know how to fix it. I have tested but i dont want to import java.util.stack in StackTest.java, because then my top() method does not work. What should I do?
The testing:
StackTest.java is an abstract test class.
For each implementation of Stack, one may simply extend StackTest with an implementing test class. The only method that should be overridden is StackTest.getIntegerStack, which should simply return an instance of a class that implements Stack. See the setUp method in StackTest and try to understand how this works.
In your case, you should extend StackTest with a test class called LinkedListTest.
you must add a call to super.setUp(); as the first line in LinkedListTest.setUp.
TODO: How should i make the getIntegerStack() do work.
stack interface class:
public interface Stack <T> {
void push ( T elem);
T pop();
T top();
int size();
boolean isEmpty();
}
LinkedList class.
import java.util.EmptyStackException;
import java.util.NoSuchElementException;
/**
* A singly linked list.
*/
public class LinkedList<T> implements Stack <T> {
private ListElement<T> first; // First element in list.
private ListElement<T> last; // Last element in list.
private int size; // Number of elements in list.
/**
* A list element.
*/
private static class ListElement<T> {
public T data;
public ListElement<T> next;
public ListElement(T data) {
this.data = data;
this.next = null;
}
}
/**
* Creates an empty list.
*/
public LinkedList() {
this.first = null;
this.last = null;
this.size = 0;
}
/**
* Inserts the given element at the beginning of this list.
*
* #param element An element to insert into the list.
*/
public void addFirst(T element) {
ListElement<T> firstElement = new ListElement<>(element);
if (this.size == 0){
this.first = firstElement;
this.last = firstElement;
}
else{
firstElement.next = this.first;
this.first = firstElement;
}
this.size ++;
}
/**
* Inserts the given element at the end of this list.
*
* #param element An element to insert into the list.
*/
public void addLast(T element) {
ListElement<T> lastElement = new ListElement<>(element);
if(this.size ==0){
this.first = lastElement;
}
else{
this.last.next = lastElement;
}
this.last = lastElement;
this.size ++;
}
/**
* #return The head of the list.
* #throws NoSuchElementException if the list is empty.
*/
public T getFirst() {
if (this.first != null){
return this.first.data;
}
else{
throw new NoSuchElementException();
}
}
/**
* #return The tail of the list.
* #throws NoSuchElementException if the list is empty.
*/
public T getLast() {
if(this.last != null){
return this.last.data;
}
else{
throw new NoSuchElementException();
}
}
/**
* Returns an element from a specified index.
*
* #param index A list index.
* #return The element at the specified index.
* #throws IndexOutOfBoundsException if the index is out of bounds.
*/
public T get(int index) {
if(index < 0|| index >= this.size){
throw new IndexOutOfBoundsException();
}
else{
ListElement<T>element = this.first;
for(int i = 0; i < index; i++){
element = element.next;
}
return element.data;
}
}
/**
* Removes the first element from the list.
*
* #return The removed element.
* #throws NoSuchElementException if the list is empty.
*/
public T removeFirst() {
if(this.first != null || this.size != 0){
ListElement<T> list = this.first;
this.first = first.next;
size --;
if(size()==0){
last = null;
}
return list.data;
}
else{
throw new NoSuchElementException();
}
}
/**
* Removes all of the elements from the list.
*/
public void clear() {
this.first = null;
this.last = null;
this.size =0;
}
/**
* Adds the element to the top of the stock.
* #param elem
*/
#Override
public void push(T elem) {
ListElement <T> list = new ListElement<>(elem);
if( first == null){
first = list;
last = first;
} else{
list.next = first;
first = list;
}
size ++;
}
/**
* Removes and returns the top element in stack,
* that is the element that was last added.
* Throws an EmptyStackException if stack is empty.
* #return the top element in the stack.
*/
#Override
public T pop(){
if(isEmpty()){
throw new EmptyStackException();
}else{
ListElement <T> list = first;
first = first.next;
size --;
return list.data;
}
}
/**
* returns the top element in the stack without removing it.
* Throws an EmptyStackException if stack is empty.
* #return the top element.
*/
#Override
public T top() {
if(isEmpty()){
throw new EmptyStackException();
}else{
return first.data;
}
}
/**
* Returns the number of elements in the stock
* #return The number of elements in the stock.
*/
public int size() {
return this.size;
}
/**
* Note that by definition, the list is empty if both first and last
* are null, regardless of what value the size field holds (it should
* be 0, otherwise something is wrong).
*
* #return <code>true</code> if this list contains no elements.
*/
public boolean isEmpty() {
return first == null && last == null;
}
/**
* Creates a string representation of this list. The string
* representation consists of a list of the elements enclosed in
* square brackets ("[]"). Adjacent elements are separated by the
* characters ", " (comma and space). Elements are converted to
* strings by the method toString() inherited from Object.
*
* Examples:
* "[1, 4, 2, 3, 44]"
* "[]"
*
* #return A string representing the list.
*/
public String toString() {
ListElement<T> listOfElements = this.first;
String returnString = "[";
while(listOfElements != null) {
returnString += listOfElements.data;
if(listOfElements.next != null){
returnString += ", ";
}
listOfElements = listOfElements.next;
}
returnString += "]";
return returnString;
}
}
Testclasses:
import org.junit.Test;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.Timeout;
import static org.junit.Assert.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import java.lang.Integer;
import java.util.EmptyStackException;
import java.util.stream.IntStream;
/**
* Abstract test class for Stack implementations.
*
* Implementing test classes must only implement the getIntegerStack
* method. Be careful not to override ANY other methods!
*
*/
public abstract class StackTest{
#Rule public Timeout globalTimeout = Timeout.seconds(5);
private Stack<Integer> stack;
private int[] valuesInStack;
private int initialStackSize;
private Stack<Integer> emptyStack;
#Before
public void setUp() {
valuesInStack = new int[] {3, 4, 1, -123, 4, 1};
initialStackSize = valuesInStack.length;
stack = getIntegerStack();
pushArrayToStack(valuesInStack, stack);
emptyStack = getIntegerStack();
}
/**
* Push an array to the stack, in order.
*
* #param array An int array.
* #param stack A Stack.
*/
private void pushArrayToStack(int[] array, Stack<Integer> stack) {
for (int i = 0; i < array.length; i++) {
stack.push(array[i]);
}
}
/**
* This is the only method that implementing classes need to override.
*
* #return An instance of Stack.
*/
protected abstract Stack<Integer> getIntegerStack();
#Test
public void topIsLastPushedValue() {
// Arrange
int value = 1338;
// Act
emptyStack.push(value);
stack.push(value);
int emptyStackTop = emptyStack.top();
int stackTop = stack.top();
// Assert
assertThat(emptyStackTop, equalTo(value));
assertThat(stackTop, equalTo(value));
}
// HELPERS
/**
* Pops the desired amount of elements.
*
* #param stack A Stack.
* #param amountOfElements The amount of elements to pop.
*/
private void popElements(Stack<Integer> stack, int amountOfElements) {
for (int i = 0; i < amountOfElements; i++) {
stack.pop();
}
}
/**
* Class used for stream operations when both actual and expected values
* need to be gather in conjunction.
*/
private class ResultPair<T> {
public final T actual;
public final T expected;
public ResultPair(T actual, T expected) {
this.actual = actual;
this.expected = expected;
}
}
}
import org.junit.Test;
import org.junit.Before;
import static org.junit.Assert.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Stack;
/**
* Test class for LinkedList
*
* The following invariants are checked for several different states and for
* each of the methods that mutate the list.
*/
public class LinkedListTest extends StackTest{
/* A sequence of integers */
private int[] elements;
/* An empty linked list */
private LinkedList<Integer> list;
#Before
public void setUp() {
super.setUp();
list = new LinkedList<Integer>();
elements = new int[]{-919, 388, 67, -248, -309, -725, 904, 53,
90, -469, -559, 256, 612, 366, -412, -221,
347, -921, -978, 324, -858, 480, -443, 891,
329, -5, 878, -538, 445, -366, 760, 52};
}
/**
* This is the only method that implementing classes need to override.
*
* #return An instance of Stack.
*/
#Override
protected Stack<Integer> getIntegerStack() {
return null;
}
}
In StackTest your abstract method protected abstract Stack<Integer> getIntegerStack(); should return the Stack interface you created. At least that's what it looks like due to no imports of classes named Stack. But in LinkedListTest the method implementation returns java.util.Stack. Note this:
import java.util.Stack;
It's the last import in LinkedListTest.
The declared method is expecting implementors to return your.package.Stack, but you are returning java.util.Stack, and those need to match, no way around that. So remove the aforementioned import, there will be no more compilation errors, and you can start testing.
Edit:
If your Stack interface does not reside in any additional packages, you should just remove the import. If you have declared it in some package of your own, you should change the import to
import your.package.Stack;
where your.package. is whatever package you declared the interface in.
About the implementation of the abstract method, you should return a new instance of Stack, as written in the comments. That means returning new instance of your LinkedList implementation.
This is for homework.
I am making a stack using a linked list. I have chosen to use the linked list from Java's java.util.LinkedList package. When I call the addFirst() method in my Main class, the program won't finish. It acts like an infinite loop, but as far as I know there are no loops involved. Here is the code:
package assignment3;
import java.util.LinkedList;
/**
*
* #author Eric
*/
public class LinkedListStack<T> {
LinkedList linkedList = new LinkedList();
public boolean isEmpty() {
if (linkedList.isEmpty()) {
return true;
} else {
return false;
}
}
public int size() {
int size = linkedList.size();
System.out.println("The size of the stack is " + size);
return size;
}
// This is the problem method.
public void push(T element) {
linkedList.addFirst(element);
}
public void pop() {
while(!linkedList.isEmpty()){
linkedList.removeFirst();
}
}
public void peek() {
while(!linkedList.isEmpty()){
linkedList.peek();
}
System.out.println("The first element in the stack is " + linkedList.peek());
}
}
This is the class Main that calls the push() method.
package assignment3;
/**
*
* #author Eric
*/
public class Main {
public static void main(String args[]) {
LinkedListStack linkedListStack = new LinkedListStack();
linkedListStack.push(1); // This never finishes.
linkedListStack.peek();
linkedListStack.size();
}
}
It's very hard to test LinkedListStack.java because I cannot push anything onto the stack. I have no idea what's wrong.
while(!linkedList.isEmpty()){
linkedList.peek();
}
peek() will never change a linked list from nonempty to empty, since it doesn't change the list.
but as far as I know there are no loops involved
What do you think while is?
I have a task to code the below class ... I have a problem in iterator() method
I have many errors in it , I do not know how to do to correct it .. Can you suggest a way to correct the code under iterator() method ... You can as well see the other parts of the class ...I put the comments from eclipse next to each infected line.. thanks
package queue;
import java.util.*;
public class FifoQueue<E> extends AbstractQueue<E> implements Queue<E> {
private QueueNode<E> last;
private int size;
public FifoQueue() {
}
/**
* Returns an iterator over the elements in this queue
* #return an iterator over the elements in this queue
*/
public Iterator<E> iterator() {
QueueNode<E> position =last;
Iterator itr = position.iterator(); // The method iterator() is //undefined for the type FifoQueue.QueueNode<E>- Iterator is a raw type. References //to generic type Iterator<E> should be
parameterized
while(itr.hasNext){ // hasNext cannot be resolved or is not a field
int object=itr.next(); //Type mismatch: cannot convert from Object to int
return object; //Type mismatch: cannot convert from int to Iterator<E>
}
}
/**
* Returns the number of elements in this queue
* #return the number of elements in this queue
*/
public int size() {
return size;
}
/**
* Inserts the specified element into this queue, if possible
* post: The specified element is added to the rear of this queue
* #param x the element to insert
* #return true if it was possible to add the element
* to this queue, else false
*/
public boolean offer(E x) {
QueueNode<E> q = new QueueNode<E>(x);
if(last!=null){
q.next=last.next;
last.next=q;
return true;
} else {
return true;
}
}
/**
* Retrieves and removes the head of this queue,
* or null if this queue is empty.
* post: the head of the queue is removed if it was not empty
* #return the head of this queue, or null if the queue is empty
*/
public E poll() {
if( last==null){
return null;
}
QueueNode<E> n=last.next;
last.next=last.next.next;
size=size-1;
return n.element;
}
/**
* Retrieves, but does not remove, the head of this queue,
* returning null if this queue is empty
* #return the head element of this queue, or null
* if this queue is empty
*/
public E peek() {
if(last==null){
return null;
}
QueueNode<E> n=last;
while(n.next !=null){
}
return n.element;
}
private static class QueueNode<E> {
E element;
QueueNode<E> next;
private QueueNode(E x) {
element = x;
next = null;
}
}
}
Your iterator() method needs to return an implementation of the Iterator<E> interface. You'd likely want to do this as a private inner class, so it has access to the queue fields.
The iterator class needs to keep the current position, and step through your nodes on calls to next().
You might want to implement fail-fast logic to prevent issues with updating the queue while iterating. Add a change counter to the queue, and increment on change (insert/remove). Remember the change counter at the time the iterator is created, and if different on a call to next(), throw ConcurrentModificationException.
This is a skeleton to get you started:
public Iterator<E> iterator() {
return new FifoIterator();
}
private final class FifoIterator implements Iterator<E> {
private QueueNode<E> curr;
FifoIterator() {
this.curr = FifoQueue.this.last;
}
#Override
public boolean hasNext() {
return (this.curr != null);
}
#Override
public E next() {
if (this.curr == null)
throw new NoSuchElementException();
this.curr = this.curr.next;
E e = this.curr.element;
if (this.curr == FifoQueue.this.last)
this.curr = null;
return e;
}
}
I've this custom class named MyAbstractList which implements MyList interface. Here's the code:
public abstract class MyAbstractList<E> implements MyList<E> {
protected int size = 0; // The size of the list
protected MyAbstractList() {
}
protected MyAbstractList(E[] objects) {
for (int i = 0; i < objects.length; i++)
add(objects[i]);
}
public void add(E e) {
add(size, e);
}
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
public boolean addAll(MyList<E> otherList) {
for (E e : otherList) {
add(e);
}
if (otherList.size() > 0)
return true;
return false;
}
public boolean removeAll(MyList<E> otherList) {
boolean removed = false;
for (E e : otherList) {
if (remove(e) && !removed)
removed = true;
}
return removed;
}
public boolean remove(E e) {
if (indexOf(e) >= 0) {
remove(indexOf(e));
return true;
} else
return false;
}
/** Retains the elements in this list that are also in otherList
* Returns true if this list changed as a result of the call */
public boolean retainAll(MyList<E> otherList) {
}
}
How to implement the retainAll() method?
MyList interface:
public interface MyList<E> extends java.lang.Iterable<E> {
/** Add a new element at the end of this list */
public void add(E e);
/** Add a new element at the specified index in this list */
public void add(int index, E e);
/** Clear the list */
public void clear();
/** Return true if this list contains the element */
public boolean contains(E e);
/** Return the element from this list at the specified index */
public E get(int index);
/** Return the index of the first matching element in this list.
* Return -1 if no match. */
public int indexOf(E e);
/** Return true if this list contains no elements */
public boolean isEmpty();
/** Return the index of the last matching element in this list
* Return -1 if no match. */
public int lastIndexOf(E e);
/** Remove the first occurrence of the element o from this list.
* Shift any subsequent elements to the left.
* Return true if the element is removed. */
public boolean remove(E e);
/** Remove the element at the specified position in this list
* Shift any subsequent elements to the left.
* Return the element that was removed from the list. */
public E remove(int index);
/** Replace the element at the specified position in this list
* with the specified element and returns the new set. */
public Object set(int index, E e);
/** Return the number of elements in this list */
public int size();
/** Adds the elements in otherList to this list.
* Returns true if this list changed as a result of the call */
public boolean addAll(MyList<E> otherList);
/** Removes all the elements in otherList from this list
* Returns true if this list changed as a result of the call */
public boolean removeAll(MyList<E> otherList);
/** Retains the elements in this list that are also in otherList
* Returns true if this list changed as a result of the call */
public boolean retainAll(MyList<E> otherList);
/** Return an iterator for the list */
public java.util.Iterator<E> iterator();
}
If elements are not Comparable you can only search for elements of your list not present in the parameter.
public boolean retainAll(MyList<E> otherList) {
boolean changed = false;
for (int i = size() - 1; i >= 0; i--) {
Object obj = get(i);
if (!otherList.contains(obj)) {
remove(i);
changed = true;
}
}
return changed;
}
Note: this algorithm is done in O(n^2), if you have list of Comparable you can go to O(n log(n))
Second note: don't use an iterator to loop the list because a change on the content of the list may throw an Exception.
Comment on suggested edit by Saud: It is not necessary to update the size. This must be done by the method remove.
Searching for info about the iterator, I found only examples that showed how to iterate over a collection, and not returning the Iterator, like I want to do.
I am practicing for the exam, so I'm trying out some programming excercises to prepare myself, and this one is about the iterator pattern.
I want to implement the getKnightPositionIterator, . You can see the code below. This code is not mine, I found this.
package iterator;
import java.util.*;
public class Position {
/** return an iterator that will return all positions
* that a knight may reach from a given starting position.
*/
public static Iterator<Position> getKnightPositionIterator(Position p) {
return null;
}
/** create a position.
* #param r the row
* #param c the column
*/
public Position(int r, int c) {
this.r = r; this.c = c;
}
protected int r;
protected int c;
/** get the row represented by this position.
* #return the row.
*/
public int getRow() { return r; }
/** get the column represented by this position.
* #return the column.
*/
public int getColumn() { return c; }
public boolean equals(Object o) {
if (o.getClass() != Position.class) { return false; }
Position other = (Position) o;
return r==other.r && c==other.c;
}
public int hashCode() {
// works ok for positions up to columns == 479
return 479*r+c;
}
public String toString() {
return "["+r+","+c+"]";
}
}
How ever, I figure that I have to create an Iterator to return, so, so far, this is my attemp.
public static Iterator<Position> getKnightPositionIterator(Position p) {
Iterator<Position> knightPosIter = Position.getKnightPositionIterator(p);
for(Iterator<Position> positions = knightPosIter; positions.hasNext(); ) {
//What should I write here?
}
return knightPosIter;
}
First, make your class implement Iterable interface
public class Position implements Iterable<Position>
and write the public Iterator<Positions> iterator(); method as outlined below instead of providing a static method in your example.
As you actually need to compute a collection of reachable positions in one way or another, you will need a structure to hold it. Any such structure will normally be iterable and, thus, will have an iterator method. So a lazy implementation could look like this:
#Override
public Iterator<Position> iterator()
{
// make sure this returns e.g. Collections.unmodifiableList
Collection<Position> positions = computeReachablePositions();
return positions.iterator();
}
In case you have some other structure to compute and store your positions that is not iterable (not advisable), implement an iterator from scratch as follows (an array of positions assumed):
#Override
public Iterator<Position> iterator()
{
// must be final to be accessible from the iterator below
final Position[] positions = computeReachablePositions();
return new Iterator<Position>() {
int index = 0;
#Override
public boolean hasNext()
{
return index < positions.length;
}
#Override
public Position next()
{
if (hasNext())
{
Position value = positions[index];
index++;
return value;
}
throw new NoSuchElementException("No more positions available");
}
#Override
public void remove()
{
throw new UnsupportedOperationException("Removals are not supported");
}};
}