Generic Array Method Class in Java - java

I've been trying to turn this generic arraylist class into an array but I haven't been able to get it to work. I've hit a roadblock at the push() and pop() methods. Any help is appreciated.
Here's the original class:
public class GenericStack<E> {
private java.util.ArrayList<E> list = new java.util.ArrayList<E>();
public int getSize() {
return list.size();
}
public E peek() {
return list.get(getSize() - 1);
}
public E push(E o) {
list.add(o);
return o;
}
public E pop() {
E o = list.get(getSize() - 1);
list.remove(getSize() - 1);
return o;
}
public boolean isEmpty() {
return list.isEmpty();
}
}
And here's my revised class so far:
public class GenericStack<E> {
public static int size = 16;
#SuppressWarnings("unchecked")
private E[] list = (E[])new Object[size];
public void add(int index, E e) {
ensureCapacity();
for (int i = size - 1; i >= index; i--) {
list[i + 1] = list[i];
list[index] = e;
size++;
}
}
public int getLength() {
return list.length;
}
public E peek() {
E o = null;
o = list[0];
return o;
}
public E push(E o) {
ensureCapacity();
list.append(o);
size++;
return o;
}
public E pop() {
E o = null;
for (int i = 0; i > list.length; i++) {
o = list[i - 1];
}
list[list.length - 1] = null;
size--;
return o;
}
private void ensureCapacity() {
if (size >= list.length) {
#SuppressWarnings("unchecked")
E[] newlist = (E[])(new Object[size * 2 + 1]);
System.arraycopy(list, 0, newlist, 0, size);
list = newlist;
}
}
public boolean isEmpty() {
if (list.length > 0) {
return false;
}
else {
return true;
}
}
}

NB: You must first correct your code like mentioned in comments.
It's recommended to use name method like of official Stack class, so there are 5 methods: empty() peek() pop() push(E item) search(Object o).
You should declare initial size of your array as a constant and an other variable for current size and all your attributes should be private like that:
private final int MAX_SIZE = 16;
private int currentSize=0;
There is the code of peek() method:
public E peek() {
E o = null;
o = list[currentSize-1];
return o;
}
There is the code of push(E o) method:
public E push(E o) {
list[currentSize]=o;
currentSize++;
return o;
}
There is the code of pop() method this method must throw EmptyStackException - if this stack is empty:
public E pop() {
E o = null;
if(currentSize>0){
o=list[currentSize - 1];
list[currentSize - 1] = null;
currentSize--;
return o;
}else{
throw new EmptyStackException();
}
}
There is the code of empty() method:
public boolean empty() {
if (currentSize > 0) {
return false;
}
else {
return true;
}
}

Related

How to extend child classes with a parent interface class

interface Iterator {
boolean hasnext();
int next();
}
class practice5 {
public static void main(String a[]) {
Stack s = new Stack();
Queue q = new Queue();
Linkedlist l = new Linkedlist();
s.push(100);
s.push(200);
q.Enque(300);
q.Enque(400);
l.add(500);
l.add(600);
Iterator itr;
itr = s;
while (!itr.hasnext()) {
System.out.println(itr.next());
}
itr = q;
while (!itr.hasnext()) {
System.out.println(itr.next());
}
itr = l;
while (itr.hasnext()) {
System.out.println(itr.next());
}
}
}
class Stack extends Iterator {
private int stack[];
private int top;
public Stack() {
stack = new int[10];
top = -1;
}
public void push(int val) {
top++;
stack[top] = val;
}
public boolean hasnext() {
if (top >= 0) {
return false;
} else {
return true;
}
}
public int next() {
return (stack[top--]);
}
}
class Queue extends Iterator {
private int queue[];
private int front, rear;
public Queue() {
queue = new int[10];
front = 0;
rear = 0;
}
public void Enque(int val) {
queue[rear] = val;
rear++;
}
public boolean hasnext() {
if (front < rear) {
return false;
} else {
return true;
}
}
public int next() {
return (queue[front++]);
}
}
class Linkedlist extends Iterator {
private int data;
private Linkedlist nw, next, prev, first, guest;
public Linkedlist() {
nw = next = prev = first = null;
}
public void add(int val) {
nw = new Linkedlist();
nw.data = val;
if (first == null) {
prev = first = nw;
} else {
prev.next = nw;
prev = nw;
}
}
public boolean hasnext() {
if (guest != 0) {
return true;
} else {
return false;
}
}
public int next() {
int curval;
curval = first.data;
first = first.next;
return (curval);
}
}
I'm expecting that I get an output for the above code.
I need to know if I'm extending the Stack, Queue and LinkedList classes wrongly with the interface class. Whenever I'm pass the iterator class object the instance of my child class objects, I am getting an error.
Also, in the LinkedList section when I call guest != 0, I'm getting an error Bad Operand. How can I check and print whether my guest is equal to zero or not?

List Interface - Java

I am working with the code below. The list interface specifies two overloaded remove() methods. I cannot figure out how to determine which one Java uses if we invoke remove(3) on a List. How can we force Java to use the other one?
public class ArrayList<E> implements List1<E> {
private E[] data;
private int size;
public ArrayList(){
data = (E[]) (new Object[1]);
size = 0;
}
public void add(E target) {
if (isFull()) {
stretch();
}
data[size] = target;
size++;
}
public boolean isEmpty() {
return size == 0;
}
protected boolean isFull() {
return size == data.length;
}
public E get(int index) {
return data[index];
}
public void set(int index, E target) {
data[index] = target;
}
public int size() {
return 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;
}
public boolean contains(E target) {
for (int i = 0; i < size; i++) {
if (data[i].equals(target)) {
return true;
}
}
return false;
}
public String toString() {
String result = "[";
for (int i = 0; i < size; i++) {
result += data[i] + "";
}
return result + "]";
}
public E remove(int index) {
E result = data[index];
for (int i = index; i < size; i++) {
data[i - 1] = data[i];
}
size--;
return result;
}
public boolean remove(E target) {
for (int i = 0; i < size; i++) {
if (data[i].equals(target)){
}
size--;
return true;
}
return false;
}
public static interface List1<E> {
public void add(E target);
public boolean contains(E traget);
public E get(int index);
public boolean isEmpty();
public E remove(int index);
public boolean remove(E index);
public void set(int index, E target);
public int size();
}
}
You have two remove() functions with different return data types and different function overloading data types. So Java would be able to distinguish those functions based on these parameters and thus will choose the appropriate function of your call. You cannot just force Java to use the other one, unless you want to call it explicitly from the first one as follows:
remove(datatype1 var1) {
remove(var2); //datatype2 of var2
//your code
}
remove(datatype2 var) {
//your code
}
If you see these two remove methods it's very clear that one take index of object in list while other take Object to delete. And the object is the Object of the Type of list. So if you want to use other one simply pass the object which is being contained by arrayList. For example:
If your list contains Integers:
List<Foo> integerList = new ArrayList<Foo>();
Foo foo = new Foo();
Foo foo1 = new Foo();
integerList.add(foo);
integerList.add(foo1);
integerList.remove(foo);//remove 1
integerList.remove(0);//remove 2
In above remove1 call the method remove(E target) will get called, on the other hand at remove 2 call the method remove(int index) will get called.

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();

Does Not Take Parameters in Java [duplicate]

This question already has answers here:
Incompatible Types Error in Java
(2 answers)
Closed 9 years ago.
I'm receiving the error "type Stack does not take parameters public class ArrayStack implements Stack" from this 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;
}
}
"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);
}
Your peek() method should like this
public E peek() throws EmptyStructureException {
if (isEmpty()) {
throw new EmptyStructureException();
}
return (E)data[size - 1];
}
Your push() method should like this
public void push(E target) {
if (isFull()) {
stretch();
}
data[size] = target;
size++;
}
Your pop() method should like this
public E pop() throws EmptyStructureException {
if (isEmpty()) {
throw new EmptyStructureException();
}
size--;
return (E)data[size];
}
Now your interface look like below
public interface Stack<E> {
public boolean isEmpty();
public E peek() throws EmptyStructureException;
public E pop() throws EmptyStructureException;
public void push(E target);
}

Type Syntax error on token(s), misplaced construct(s)

package list;
public class LinkedList implements List {
//Datenfeld
private Element item;
//Zeigerfeld
private LinkedList next;
//Konstruktor, erzeugt leere Liste
public LinkedList() {
item = null;
next = null;
}
//Selektoren
public Object getItem() {
return item;
}
public LinkedList next() {
return next;
}
//ist die Liste leer?
public boolean isEmpty() {
return next == null;
}
public Object firstElement() {
if (isEmpty())
return null;
else
return next.item;
}
public int length() {
if (isEmpty())
return 0;
else
return 1 + next.length();
}
//fügt x am Kopf ein
public LinkedList insert(Element x) {
LinkedList l = new LinkedList();
l.item = x;
l.next = next;
next = l;
return this;
}
//hängt das x ans Ende der Liste und liefert Teilliste
public LinkedList append (Element x) {
if (isEmpty())
return insert(x);
else
return next.append(x);
}
//liefert Null, falls x nicht in Liste
//sonst Teilliste
private LinkedList find(Element x) {
if (isEmpty())
return null;
else
if (firstElement().equals(x))
return this;
else
return next.find(x);
}
//entfertn erstes x der Liste
public LinkedList delete(Element x) {
LinkedList l = find(x);
if (l != null)
return l.next = l.next.next;
else
return this;
}
//entfernt das erste Element der Liste
public LinkedList delete() {
if (!isEmpty())
next = next.next;
return this;
}
public boolean isInList(Element x) {
return(find(x) != null);
}
public String toString() {
return (next == null ? " |--" : " --> " + next.item + next);
}
static void println(Element x) {
System.out.println(x.toString());
}
public LinkedList add(Element x, int n) {
return null;
}
public LinkedList remove(int n) {
return null;
}
public Element get(int n) {
return null;
}
public int firstIndexOf(Element x) {
return 1;
}
public int lastIndexOf(Element x) {
return 1;
}
LinkedList l1 = new LinkedList();
l1.insert("AA");
}
In the last line (l1.insert("AA"); I get the error
Type Syntax error on token(s), misplaced construct(s).
Need help. Can't find the problem.
You can't have random statements like that outside of methods. You need to put that statement in a method, or build a class that uses your linked lists and does that insert.

Categories

Resources