This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java how to: Generic Array creation
import java.util.EmptyStackException;
import java.util.Vector;
public class Stack<E> extends Vector<E> {
private E a[];
private int top;
public void Stack() {
a = new E[100];
top = -1;
}
public void Stack(int n) {
a = new E[n];
top = -1;
}
public E pop() {
E obj;
int len = size();
if (top == -1)
throw new EmptyStackException();
else
obj = a[top--];
return obj;
}
public void push(E e) {
if (e == null)
throw new NullPointerException();
else if (top == size() - 1)
System.out.println("Stack full");
else {
a[++top] = e;
System.out.println("pushed :" + e);
}
}
public int size() {
int i;
for (i = 0; a[i] != null; i++)
;
return i;
}
}
This is my stack generics class in java. I am getting an error in array declaration inside the two constructor i.e Stack() and Stack(int n). The error is "generic array creation" in both cases. please help
generic array is can not be created. so use Object array.
import java.io.*;
import java.util.EmptyStackException;
import java.util.Vector;
public class Stack extends Vector
{
private Object a[];
private int top;
public void Stack()
{
a=new Object[100];
top=-1;
}
public void Stack(int n)
{
a=new Object[n];
top=-1;
}
public E pop()
{
E obj;
int len = size();
if (top == -1)
throw new EmptyStackException();
else
obj=(E) a[top--];
return obj;
}
public void push(E e)
{
if(e==null)
throw new NullPointerException();
else if(top==size()-1)
System.out.println("Stack full");
else
{
a[++top]=e;
System.out.println("pushed :"+e);
}
}
public int size()
{
int i;
for(i=0;a[i]!=null;i++);
return i;
}
}
You do not have constructors in your class these are methods. for construtors remove the void type. Constructors don't have return types. Also your class name starts with lower letter stack and constructors start with Stack . Rename your class to Stack and remove void types.
You need to do it like this
public Stack(Class<E> cls)
{
a = (E[]) Array.newInstance( cls);
top=-1;
}
public Stack(Class<E> cls,int n)
{
a = (E[]) Array.newInstance( cls,n);
top=-1;
}
see Generic Array
Following is your working class with object creation in main method.
class Stack<E> extends Vector<E> {
private E a[];
private int top;
public Stack(Class<E> cls)
{
a = (E[]) Array.newInstance( cls);
top=-1;
}
public Stack(Class<E> cls,int n)
{
a = (E[]) Array.newInstance( cls,n);
top=-1;
}
public E pop() {
E obj;
int len = size();
if (top == -1)
throw new EmptyStackException();
else
obj = a[top--];
return obj;
}
public void push(E e) {
if (e == null)
throw new NullPointerException();
else if (top == size() - 1)
System.out.println("Stack full");
else {
a[++top] = e;
System.out.println("pushed :" + e);
}
}
public int size() {
int i;
for (i = 0; a[i] != null; i++)
;
return i;
}
public static void main(String...strings ){
Stack<Integer> st=new Stack<Integer>(Integer.class,n);
}
}
Related
public class StackSimple{
private long capacity=1000;//maximum size of array
private int idx_top;
private Object data[];
public StackSimple(int capacity)
{
idx_top=-1;
this.capacity=capacity;
data = new Object[capacity];
}
public boolean isEmpty(){
return(idx_top<0);
}
public boolean isFull(){
return(idx_top>=capacity-1);
}
public int size()
{
return idx_top+1;
}
public boolean push(Object x){
if (isFull()){
throw new IllegalArgumentException("ERROR:Stack Overflow.Full Stack");
}
else
{`enter code here`data[++idx_top]=x;
return true;
}
}
public Object pop(){
if(isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else{
return data[idx_top--];
}
}
public Object top(){
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else{
return data[idx_top];
}
}
public void print()
{`
for (int i=size()-1;i>=0;i--)
System.out.println(data[i]);
}
}
public class Stack_Exercise {
public static void main(String[] args) {
StackSimple s = new StackSimple(capacity:3);//error shows here
s.push(x:"books");`enter code here`
s.push(x:"something");
s.push(x:"200");
s.print();
System.out.println("Size=" +s.size());
}
}
Why doesn't this work?
Why does it say invalid statement while creating the StackSimple object? The problem is in the main class while running it. There are errors while pushing the elements.
Error while compiling
When passing parameters to a function you just pass the values.
In your case not StackSimple(capacity:3) but just StackSimple(3)
First question, which version of Java are you using.
Second, in Java you should be passing as a variable instead of StackSimple(capacity:3). Change your main method to below, here is my recommendation:
StackSimple s = new StackSimple(3);
s.push("books");
s.push("something");
s.push("200");
s.print();
System.out.println("Size=" +s.size());
You are not at all pushing the value in the stack, your pusch function is not working as it is expected to work.
Here is the correct program.
class StackSimple {
private long capacity = 1000;// maximum size of array
private int idx_top;
private Object data[];
public StackSimple(int capacity) {
idx_top = -1;
this.capacity = capacity;
data = new Object[capacity];
}
public boolean isEmpty() {
return (idx_top < 0);
}
public boolean isFull() {
return (idx_top >= capacity - 1);
}
public int size() {
return idx_top + 1;
}
public boolean push(Object x) {
if (isFull()) {
throw new IllegalArgumentException("ERROR:Stack Overflow.Full Stack");
} else {
data[++idx_top] = x;
return true;
}
}
public Object pop() {
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else {
return data[idx_top--];
}
}
public Object top() {
if (isEmpty())
throw new IllegalArgumentException("ERROR:Stack Underflow.Empty Stack.");
else {
return data[idx_top];
}
}
public void print() {
for (int i = size() - 1; i >= 0; i--)
System.out.println(data[i]);
}
}
public class test {
public static void main(String[] args) {
StackSimple s = new StackSimple(3);// error shows here
s.push("books");
s.push("something");
s.push("200");
s.print();
System.out.println("Size=" + s.size());
}
}
I am implementing an immutable queue using the following code :
import java.util.NoSuchElementException;
import java.util.Queue;
public class ImmutableQueue<E> {
//Two stacks are used. One is to add items to the queue(enqueue) and
//other is to remove them(dequeue)
E returnedItem;
private ImmutableQueue(ReversableStack<E> order, ReversableStack<E> reverse) {
this.order = order;
this.reverse = reverse;
}
//initially both stacks are empty
public ImmutableQueue() {
this.order = ReversableStack.emptyStack();
this.reverse = ReversableStack.emptyStack();
}
public ImmutableQueue<E> enqueue(E e) {
if (null == e)
throw new IllegalArgumentException();
return new ImmutableQueue<E>(this.order.push(e), this.reverse);
}
public ImmutableQueue<E> dequeue() {
if (this.isEmpty())
throw new NoSuchElementException();
if (!this.reverse.isEmpty()) {
returnedItem = this.reverse.head;
return new ImmutableQueue<E>(this.order, this.reverse.tail);
} else {
returnedItem = this.reverse.head;
return new ImmutableQueue<E>(ReversableStack.emptyStack(),
this.order.getReverseStack().tail);
}
}
private static class ReversableStack<E> {
private E head; //top of original stack
private ReversableStack<E> tail; //top of reversed stack
private int size;
//initializing stack parameters
private ReversableStack(E obj, ReversableStack<E> tail) {
this.head = obj;
this.tail = tail;
this.size = tail.size + 1;
}
//returns a new empty stack
public static ReversableStack emptyStack() {
return new ReversableStack();
}
private ReversableStack() {
this.head = null;
this.tail = null;
this.size = 0;
}
//Reverses the original stack
public ReversableStack<E> getReverseStack() {
ReversableStack<E> stack = new ReversableStack<E>();
ReversableStack<E> tail = this;
while (!tail.isEmpty()) {
stack = stack.push(tail.head);
tail = tail.tail;
}
return stack;
}
public boolean isEmpty() {
return this.size == 0;
}
public ReversableStack<E> push(E obj) {
return new ReversableStack<E>(obj, this);
}
}
private ReversableStack<E> order;
private ReversableStack<E> reverse;
private void normaliseQueue() {
this.reverse = this.order.getReverseStack();
this.order = ReversableStack.emptyStack();
}
public E peek() {
if (this.isEmpty())
throw new NoSuchElementException();
if (this.reverse.isEmpty())
normaliseQueue();
return this.reverse.head;
}
public boolean isEmpty() {
return size() == 0;
}
//returns the number of items currently in the queue
public int size() {
return this.order.size + this.reverse.size;
}
public static void main(String[] args)
{
ImmutableQueue<Integer> newQueue = new ImmutableQueue<Integer>();
newQueue=newQueue.enqueue(5);
newQueue=newQueue.enqueue(10);
newQueue=newQueue.enqueue(15);
//newQueue = newQueue.dequeue();
//System.out.print(newQueue);
int x = newQueue.peek();
//ImmutableQueue<Integer> x = newQueue.dequeue();
System.out.println(x);
}
}
The dequeue function does not seem to return the removed item, it only removes it. This the commented line by the way. How do I access the removed item ?
I have created a variable of type E in the main class. Now how do I access it in main and get the dequed value ?
Thanks
I have made a Priority Queue class with an array list, but I am having trouble with the insert and delMin (delete minimum areas). I cannot create more functions and here is my code:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class MyMinPQ<E extends Comparable<E>> implements Iterable<E> {
private ArrayList<E> pq;
private int N;
public MyMinPQ() {
pq = new ArrayList<E>();
}
public E delMin(){
E minVal = min();
pq.remove(0);
N--;
return minVal;
}
public E min (){
if (isEmpty())
throw new NoSuchElementException();
return pq.get(0);
}
public void insert (E item){
for (int i = 0; i < N; i++){
pq.add(item);
if (pq.get(i) > pq.get(i+1)) {
E tmp = pq.get(i);
pq.set(i+1, tmp);
}
}
N++;
}
public boolean isEmpty() {
return N == 0;
}
public int size() {
return N;
}
public Iterator<E> iterator() {
return new Iterator<E>(){
int current = 0;
public boolean hasNext() {
return current != size();
}
public E next() {
if (hasNext())
return pq.get(current++);
else throw new NoSuchElementException( );
}
public void remove() {
throw new UnsupportedOperationException( );
}
};
}
}
At the insert portion of the code, I know that I have to sort the new additions to Arraylist but I am having issues with going about this. I tried to compare the values that is within the list, but eclipse does not allow it based on how I formatted it. When I use compareTo, it does not work with my iterator and everything goes into disarray.
My question is how can I go about modifying my insert function so it can sort new items in descending order? Will my delMin() also have to change because of it?
try this
public void insert(E item) {
int i = 0;
while (i < N && pq.get(i).compareTo(item) <= 0) {
i++;
}
N++;
}
public X get(int index)
{
if (index >= 0)
{
Node<X> i = head;
int c = 0;
while (c < index)
{
i = i.getLink();
c++;
}
return i.getValue();
}
else
{
throw new ArrayIndexOutOfBoundsException();
}
}
.
#Test
public void testGet12()
{
LList<String> b = new LList<String>();
b.add("str1");
b.add("str2");
b.add("str3");
b.add("str4");
b.add("str5");
b.add("str6");
b.add("str7");
b.add("str8");
b.add("str9");
b.add("str10");
b.add("str11");
b.add("str12");
assertEquals("str8", b.get(7));
assertEquals("str12", b.get(11));
assertEquals("str1", b.get(0));
}
It is saying that it's expecting str8, but is getting str5, why is my index off by 3? Am i missing something here? To me it seems when it doesnt reach the index it goes up one link until it finally reaches it then spits out the value.
Just an idea
import java.util.ArrayList;
import java.util.List;
public class list {
static List<String> a=new ArrayList<String>();
public String getvalue(int index)
{
return a.get(index);
}
public static void main(String args[]){
list e=new list();
a.add("Str0");
a.add("Str1");
a.add("Str2");
a.add("Str3");
a.add("Str4");
a.add("Str5");
a.add("Str6");
a.add("Str7");
a.add("Str8");
if("Str6".equals(e.getvalue(6))){
System.out.println("true");
}
else
System.out.println("Wrong");
}
}
My binary tree looks pretty close to my class materials, but when I print to the console or check for contains(), any adds I'm doing aren't registered.
I don't have a great understanding of static and the debugger is giving me a hint about making a static reference to non-static variable overallRoot, but everything compiles without error or warning in eclipse.
public class BSTSimpleSet<E extends Comparable<E>> implements SimpleSet<E> {
private GTNode<E> overallRoot;
private int size;
public static void main(String[] args) {
BSTSimpleSet<Integer> main = new BSTSimpleSet<Integer>(2);
main.toString();
main.add(3);
main.toString();
main.add(4);
main.toString();
main.add(5);
main.toString();
System.out.print(main.contains(3));
}
public BSTSimpleSet() {
size = 0;
}
public BSTSimpleSet(E input) {
overallRoot = new GTNode<E>(input);
size = 1;
}
public boolean add(E e) {
return add(e, overallRoot);
}
private boolean add(E e, GTNode<E> root) {
if (root == null) {
root = new GTNode<E>(e);
size++;
return true;
} else {
int compare = e.compareTo(root.data);
if (compare == 0) {
return false;
} else if (compare < 0) {
return add(e, root.left);
} else {
return add(e, root.right);
}
}
}
public void clear() {
overallRoot = null;
}
public boolean contains(E e) {
return contains(e, overallRoot);
}
private boolean contains(E e, GTNode<E> root) {
if (root == null) {
return false;
} else {
int compare = e.compareTo(root.data);
if (compare == 0) {
return true;
} else if (compare < 0) {
return contains(e, root.left);
} else {
return contains(e, root.right);
}
}
}
public boolean isEmpty() {
if (overallRoot == null) {
return false;
} else {
return true;
}
}
public int size() {
return size;
}
public String toString() {
this.toString(overallRoot, 0);
return null;
}
private void toString(GTNode<E> root, int level) {
if (root != null) {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println(root.data);
toString(root.left, level + 1);
toString(root.right, level + 1);
} else {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println("_");
}
}
private static class GTNode<E extends Comparable<E>> {
public E data;
public GTNode<E> left;
public GTNode<E> right;
public GTNode(E input) {
this(input, null, null);
}
public GTNode(E input, GTNode<E> lNode, GTNode<E> rNode) {
data = input;
left = lNode;
right = rNode;
}
}
}
This code does absolutely nothing.
private boolean add(E e, GTNode<E> root) {
if (root == null) {
root = new GTNode<E>(e);
size++;
return true;
}
...
Java passes in the Object Reference to a method. If you change the Reference, that will not
be propagated back to the calling method. If you change what the Reference refers to
that will be propagated back.
eg
// arrays behave the same way so using them to illustrate.
public void callMethods(){
int[] array = new int[1];
array[0] = 0;
doesNotChange(array);
System.out.println(array[0]);// will print 0
doesAChange(array);
System.out.println(array[0]);// will print 1
}
public void doesNotChange(int[] myArray){
myArray = new int[1];
myArray[0] = 1;
}
public void doesAChange(int[] myArray){
myArray[0] = 1;
}
To avoid these sorts of things I recommend always setting method parameters final.
The GTNode class shouldn't be static. Static classes are classes with only static methods, which means they don't have to be instantiated. The prototypical example of this is the java.lang.Math class: You don't need to call something like Math m = new Math(); m.cos(); to get the cosine, you just call Math.cos(). Since you're creating multiple instances of the GTNode class, make it non-static and you should be good.