Is this code a stack?
How I can make it better?
This is my first one.
Can i do this using ArrayList?
public class Stack implements IADT {
private final int[] stackArray = new int[10];
private int top;
private int nr;
public Stack(){
top = -1;
}
#Override
public String pop() {
return Integer.toString(stackArray[top--]);
}
#Override
public String peek() {
return Integer.toString(stackArray[top]);
}
#Override
public void push(String value) {
//...
}
I didn't added the isEmpty() method.
Yes, it is.
But you can add checking for overflow, underflow.
And this will be better if you'll try using collections.
Related
Here is my code. I have a weird error that I cant figure out. Any and every help would be greatly appreciated. I am a beginner at this level.
public interface QueueInterface<T>
{
public void enqueue(T newEntry);
public T dequeue();
public T getFront();
public boolean isEmpty();
public void clear();
Now I am putting the code for Vector Class which is implemented by the above code. I need help on this part. I think there is an error in the for loop but I am not sure.
import java.util.Vector;
public class VectorQueue implements QueueInterface
{
private Vector queue;
private int frontIndex;
private int backIndex;
private boolean initialized=false;
private static final int DEFAULT_CAPACITY= 50;
private static final int MAX_CAPACITY= 1000;
public VectorQueue()
{
queue=new Vector<>();
frontIndex=backIndex=0;
}
public void enqueue(T newEntry)
{
backIndex++;
queue.add(backIndex, newEntry);
if(frontIndex==0)
frontIndex++;
}
public T dequeue()
{
if(frontIndex!=0)
{
T rEntry=queue.elementAt(frontIndex);
for (int i =frontIndex;i++)
queue.add(frontIndex, queue.elementAt(frontIndex+1));
queue.remove(backIndex);
backIndex--;
if(backIndex==0)
frontIndex=0;
return rEntry;
}
return null;
}
public T getFront()
{
if(frontIndex!=0)
return queue.elementAt(frontIndex);
return null;
}
public boolean isEmpty()
{
if(backIndex==0)
return true;
return false;
}
public void clear()
{
int index=backIndex;
for(int i=frontIndex;i<=backIndex;i++)
queue.removeElementAt(index--);
frontIndex=backIndex=0;
}
}
I have been following along in the book Data Structures (Into Java) by Paul Hilfinger and I am having trouble implementing some part of a Tree structure.
When during the implementation, the book suggested that we have a nested static class represent an empty tree to make so methods using a Tree do not have to check for null pointers. The example code looks like this
public class Tree<T> {
public Tree(T label) ...
public Tree(T label, int k) ...
public T label() ...
public int degree() ...
public int numChildren() ...
public Tree<T> child(int k) ...
public void setChild(int k, Tree<T> C) ...
public boolean isEmpty() { return false }
public final Tree<T> EMPTY = new EmptyTree();
static class EmptyTree<T> extends Tree<T> {
private EmptyTree() {}
public boolean isEmpty() { return true }
public int degree() { return 0 }
public int numChildren() { return 0 }
public Tree<T> getChild(int i) {
throw new Exception;
}
public T label() {
throw new Exception;
}
}
}
Here is my implementation:
public class NonEmptyGTree<T> {
public NonEmptyGTree(T label, int arity) {
this.label = label;
children = (NonEmptyGTree<T>[]) new Object[arity];
for (int i = 0; i < arity; i++)
children[i] = EMPTY;
}
public NonEmptyGTree() {
}
public NonEmptyGTree<T> getChild(int i) {
return children[i];
}
public void setChild(int i, NonEmptyGTree<T> set) {
if (children[i].isEmpty()) deg += 1;
children[i] = set;
}
public T getLabel() {
return label;
}
public void setLabel(T label) {
this.label = label;
}
public int numChildren() {
return children.length;
}
public int degree() {
return deg;
}
public boolean isLeaf() {
return deg == 0;
}
public boolean isEmpty() {
return false;
}
public class EmptyGTree<T> extends NonEmptyGTree<T> {
private EmptyGTree() {}
public int degree() { return 0; }
public int numChildren() {
return 0;
}
public NonEmptyGTree<T> getChild(int i) {
throw new IllegalStateException();
}
public void setChild(int i, NonEmptyGTree<T> set) {
throw new IllegalStateException();
}
public T getLabel() {
throw new IllegalStateException();
}
public void setLabel(T label) {
throw new IllegalStateException();
}
public boolean isEmpty() {
return true;
}
}
private T label;
private NonEmptyGTree[] children;
private int deg = 0;
public final NonEmptyGTree<T> EMPTY = new EmptyGTree<T>();
}
This made sense to me since that way we won't have to check for null pointers when we use trees elsewhere, but when I try to initialize a tree, it goes into a loop with the Tree initializing EMPTY then EMPTY calling super() which then initializes Tree again looping.
I then tried to use a Null design pattern where I made a Tree interface and and then had two files implementing it, one for an empty tree and a nonempty tree. This seems messy to me because then for any subtype of a Tree, I would have to split it up into a nonempty tree and empty tree for every subtype. It seems like the idea of making an empty tree should stop with just this one implementation since functionally all empty trees are the same (if you do not need to access the parent nodes).
Is it not possible to make it so that I would only have to implement the EmptyTree once? Or is what I am asking to do not possible?
I created a priority queue which contains QueueItem objects. But even though I have already implemented getPriority() in the QueueItem class, it still says cannot resolve method getPriority() in the method insert() of the PriorityQueue class.
Here is my PriorityQueue class:
public class PriorityQueue<QueueItem> implements Iterator<QueueItem> {
private int maxSize;
private int size;
private Map<Integer, List<QueueItem>> pq;
public PriorityQueue(int maxSize) {
if (maxSize < 0) throw new IllegalArgumentException();
this.maxSize = maxSize;
pq = new HashMap<Integer, List<QueueItem>>();
}
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
public void insert (QueueItem item) {
int priority = item.getPriority(); //here is where the problem occured
// pq.get(priority)
}
}
Here is my QueueItem class:
public class QueueItem implements Comparable{
private int priority;
private Object value;
public QueueItem() {
priority = -1;
value = null;
}
public QueueItem(int priority, Object value) {
this.priority = priority;
this.value = value;
}
public int getPriority() {
return priority;
}
public Object getValue() {
return value;
}
public int compareTo(Object o) {
if (!(o instanceof QueueItem)) throw new ClassCastException();
if (((QueueItem)o).getPriority() == -1) throw new NullPointerException();
return priority - ((QueueItem) o).getPriority();
}
}
As you can see, the method getPriority() simply returns an integer priority.
I appreciate in advance if anyone could point out the error I have made. Thanks.
OH. It was staring me in the face.
public class PriorityQueue<QueueItem> implements Iterator<QueueItem> {
// ^^^^^^^^^^^
You're declaring a type variable here with the same name as the class QueueItem which shadows it.
So I think you just want to remove that:
public class PriorityQueue implements Iterator<QueueItem> {
If you intended for PriorityQueue to be generic then I'm not sure exactly what you need to do to fix it. Perhaps you would want something like this:
public class PriorityQueue<E> implements Iterator<QueueItem<E>> {
...
private Map<Integer, List<QueueItem<E>>> pq;
...
}
public class QueueItem<E> implements Comparable<QueueItem<E>> {
...
private E value;
...
}
As a side note, using the raw type Comparable isn't good. Even with the non-generic class QueueItem you should have implements Comparable<QueueItem>.
I want to create a fixed-size stack and truncate the stack when is full. For this already exists a approach in Creating a fixed-size Stack, but I do not want to implement a class.
It is possible to do something like this?
Stack<String> stack = new Stack<String>(){
private static final long serialVersionUID = 1L;
public String push(String item) {
if (this.size() == FIXED_SIZE) {
//truncate()
}
return super.push(item);
}
};
And the rest of the stack methods remain the same?
So this is what I found in the documentation. I did not use or tested it. So I am not sure how this would work out. Because removeElementAt() is inherited from Vector class, and I am hoping that removeElementAt(0), will still remove the element at the bottom.
Stack<String> stack = new Stack<String>(){
private static final long serialVersionUID = 1L;
public String push(String item) {
if (this.size() == FIXED_SIZE) {
this.removeElementAt(0);
}
return super.push(item);
}
};
And also I am assuming that, what you meant by truncate is to remove the first-in element currently in the list, if you just want to reject the new coming element, you can just return null.
How about something like this:
Public class TruncatedStack<T> extends FixedStack<T>
{
private static final long serialVersionUID = 1L;
#Override
public String push(String item) {
if (this.top == size) {
this.top = -1;
return super.push(item);
}
}
Wrote this off the top of my head (untested). As mentioned in the comments, a fixed size stack is simply an array with a counter to keep track of the top.
public class FixedSizeStack {
int top, numElements;
int[] baseArray;
public FixedSizeStack(int maxSize) {
top = 0;
numElements = 0;
baseArray = new int[maxSize];
}
public void push(int num) {
baseArray[top] = num;
top = (top+1) % baseArray.length;
numElements++;
}
public int pop(int num) {
if(numElements == 0) return null; //or throw exception--you've removed too many elements!
numElements--;
top = (top == 0) ? (baseArray.length - 1) : (top - 1);
return baseArray[top];
}
}
Yep, you are almost exactly right. You just need to do a this.remove(0) and then you're done.
Stack<String> stack = new Stack<String>(){
#Override
public String push(String item) {
if (this.size() == FIXED_SIZE) {
this.remove(0)
}
return super.push(item);
}
};
Is there any simple way to get the stack to display then empty itself inside the method "PrintAndEmpty"? I need the print and empty inside the method PrintAndEmpty and not the main. The codes are:
import java.util.*;
class Stack<E> implements StackInterface<E> {
private ArrayList<E> items;
public Stack() { // default constructor; creates an empty stack
items = new ArrayList<E>(); // initial capacity is 10
}
public Stack(int initialCapacity) {
//one argument constructor, creates a stack with initial capacity initialCapacity
items = new ArrayList<E>(initialCapacity);
}
public void push(E x) {
items.add(x); //uses the ArrayList method add(E o)
}
public E pop() {
if (empty()) // determine whether or not there is an item to remove
return null;
return items.remove(items.size()-1); //uses the ArrayList method remove(int n)
}
public boolean empty() {
return items.isEmpty();//uses the ArrayList method isEmpty()
}
public int size() {
return items.size(); //uses the ArayList method size()
}
public E peek() {
if (empty()) // determine whether or not there is an item on the stack
return null;
return items.get(items.size()-1); //uses the ArrayList method get(int i)
}
public void PrintAndEmpty()
{
// I want to print then empty the stack here, not in the main method.
}
Main method
public static void main (String[] args) // for demonstration only
{
Stack<Student> s = new Stack<Student>();
// push five Student references onto s
s.push(new Student("Spanky", "1245"));
s.push(new Student("Alfalfa", "1656"));
s.push(new Student("Darla", " 6525"));
s.push(new Student("Stimie", "1235"));
s.push(new Student("Jackie", "3498"));
// The data below is what I am trying to put in the PrintAndEmpty method
while(!s.empty())
System.out.println(s.pop().getName());
System.out.println();
System.out.println("The size of the stack is now "+s.size());
}
The Student Class for testing purposes:
public class Student
{
private String name;
private String id;
public Student()
{
name = "";
id = "";
}
public Student (String n, String idNum)
{
name = n;
id = idNum;
}
public String getName()
{
return name;
}
public String getID()
{
return id;
}
public void setName(String n)
{
name = n;
}
public void setID( String idNum)
{
id = idNum;
}
public boolean equals(Object o) // name and id are the same
{
return ( (((Student)o).name).equals(name) &&
(((Student)o).id).equals(id) );
}
}
I am all out of ideas as far as getting this to work. If anyone has suggestions, please let me know. I would greatly appreciate it!
Not sure why you'd want to do that, but here is how you would do it:
// PrintAndEmpty 'this' stack.
public void PrintAndEmpty()
{
// The condition to check - e.g. 'this' stack.
while(!this.empty()) {
// Pop from the stack - e.g. 'this' stack.
System.out.println(this.pop().getName());
}
}