List Interface - Java - 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.

Related

Generic stack implementation

I'm trying to implement a generic stack.
Here's the interface
package stack;
public interface Stack<T>{
void push(T number);
T pop();
T peek();
boolean isEmpty();
boolean isFull();
}
Here's the class
package stack;
import java.lang.reflect.Array;
import java.util.EmptyStackException;
public class StackArray <T> implements Stack<T>{
private int maxSize;
private T[] array;
private int top;
public StackArray(int maxSize) {
this.maxSize = maxSize;
// #SuppressWarnings("unchecked")
this.array = (T[]) Array.newInstance(StackArray.class, maxSize);
this.top = -1;
}
private T[] resizeArray() {
/**
* create a new array double the size of the old, copy the old elements then return the new array */
int newSize = maxSize * 2;
T[] newArray = (T[]) Array.newInstance(StackArray.class, newSize);
for(int i = 0; i < maxSize; i++) {
newArray[i] = this.array[i];
}
return newArray;
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == maxSize-1;
}
public void push(T element) {
if(!this.isFull()) {
++top;
array[top] = element;
}
else {
this.array = resizeArray();
array[++top] = element;
}
}
public T pop() {
if(!this.isEmpty())
return array[top--];
else {
throw new EmptyStackException();
}
}
public T peek() {
return array[top];
}
}
Here's the Main class
package stack;
public class Main {
public static void main(String[] args) {
String word = "Hello World!";
Stack <Character>stack = new StackArray<>(word.length());
// for(Character ch : word.toCharArray()) {
// stack.push(ch);
// }
for(int i = 0; i < word.length(); i++) {
stack.push(word.toCharArray()[i]);
}
String reversedWord = "";
while(!stack.isEmpty()) {
char ch = (char) stack.pop();
reversedWord += ch;
}
System.out.println(reversedWord);
}
}
The error is
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Character
at stack.StackArray.push(StackArray.java:40)
at stack.Main.main(Main.java:14)
line 40 is in the push method
array[top] = element;
Side Question:
Any way to suppress the warning in the constructor? :)
The underlying issue is type erasure. The relevant implications of this means that an instance of the Stack class doesn't know it's type arguments at run-time. This is the reason why you can't just use the most natural solution here, array = new T[maxSize].
You've tried to work around this by creating an array using Array.newInstance(...), but unfortunately this array does not have elements of type T either. In the code shown the elements are of type StackArray, which is probably not what you intended.
One common way of dealing with this is to use an array of Object internally to Stack, and cast any return values to type T in accessor methods.
class StackArray<T> implements Stack<T> {
private int maxSize;
private Object[] array;
private int top;
public StackArray(int maxSize) {
this.maxSize = maxSize;
this.array = new Object[maxSize];
this.top = -1;
}
// ... lines removed ...
public T pop() {
if(this.isEmpty())
throw new EmptyStackException();
return element(top--);
}
public T peek() {
if(this.isEmpty())
throw new EmptyStackException();
return element(top);
}
// Safe because push(T) is type checked.
#SuppressWarnings("unchecked")
private T element(int index) {
return (T)array[index];
}
}
Note also you have a bug in the resizeArray() method where maxSize is never assigned a new value. You don't really need to keep track of maxSize, as you could just use array.length.
I think there is also an issue with peek() when the stack is empty in the original code.
Your code creates arrays of StackArray, and then you try to stick Character objects in it, just as if you were doing this:
static void add(Object arr[], Object o) {
arr[0] = o;
}
public static void main(String[] args) {
StackArray stack[] = new StackArray[1];
Character c = 'x';
add(stack, c);
}

Generic Array Method Class in 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;
}
}

Why am I getting a Class Cast Exception?

The assignment reads:
Give a complete implementation of a priority queue using an array of ordinary queues. For your ordinary queue, use the version...on page 402.
Pg402 reads:
public class PriorityQueue<E>
{
private ArrayQueue<E>[] queues;
...
In this implementation, the constructor allocates the memory for the array of queues with the statement:
queues = (ArrayQueue<E>[]) new Object[highest+1];
However:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Lpriorityqueue.Queue;
at priorityqueue.PriorityQueue.(PriorityQueue.java:17)
at priorityqueue.PriorityQueue.main(PriorityQueue.java:67)
Java Result: 1
Exception on data = (Queue<T>[]) new Object[highPriority];
public class PriorityQueue<T>
{
private Queue<T>[] data;
private int size, hprior;
#SuppressWarnings("unchecked")
public PriorityQueue(int highPriority)
{
if(highPriority < 1)
throw new RuntimeException("Invalid priority number!");
data = (Queue<T>[]) new Object[highPriority]; //Error line 17
for(int i = 0; i < highPriority; i++)
{
data[i] = new Queue<>();
}
size = 0;
}
public void add(int priority, T element)
{
if(priority > data.length)
throw new RuntimeException("Invalid priority number!");
data[priority-1].enqueue(element);
size++;
}
public T remove()
{
if(empty())
throw new RuntimeException("Priority Queue is Empty!");
T element = null;
for(int i = data.length; i < 0; i--)
{
if(data[i].size()!=0)
element = (T) data[i].dequeue();
break;
}
return element;
}
public int size()
{
return size;
}
public boolean empty()
{
return size == 0;
}
public static void main(String[] args)
{
PriorityQueue<String> pq = new PriorityQueue<>(10); //Error at line 67
pq.add(1, "hi");
pq.add(2, "there!");
System.out.println(pq.remove());
}
}
class Queue<T>
{
private int front, rear, size;
public final static int DEFAULT_CAPACITY = 64;
private T[] queue;
public Queue(int capacity)
{
queue = (T[]) new Object[capacity];
size = 0;
front = 0;
rear = 0;
}
public Queue()
{
this(DEFAULT_CAPACITY);
}
public void enqueue(T element)
{
if(size() == queue.length)
throw new RuntimeException("Queue Full!");
queue[rear]= element;
rear = (rear +1) % queue.length;
size++;
}
public T dequeue()
{
if(empty())
throw new RuntimeException("Queue empty!");
T element = queue[front];
front = (front +1) % queue.length;
size--;
return element;
}
public int size()
{
return size;
}
public T front()
{
return queue[front];
}
public boolean empty()
{
return size == 0;
}
}
You can't randomly cast Object to some other type. If you want a Queue<T>[], you need to actually construct one. You can't really create an array with generics, so you're going to have to do something like this:
Queue<T>[] queue = (Queue<T> []) new ArrayDeque[10]; //or whatever concrete implementation you want.

adding an iterator to my arraylist

import java.util.Iterator;
public class MyArrayList<E> implements Iterable<E> {
public static final int DEFAULT_SIZE = 5;
public static final int EXPANSION = 5;
private int capacity;
private int size;
private Object[] items;
public MyArrayList() {
size = 0;
capacity = DEFAULT_SIZE;
items = new Object[DEFAULT_SIZE];
}
private void expand() {
Object[] newItems = new Object[capacity + EXPANSION];
for (int j = 0; j < size; j++) newItems[j] = items[j];
items = newItems;
capacity = capacity + EXPANSION;
}
public void add(Object obj) {
if (size >= capacity) this.expand();
items[size] = obj;
size++;
}
public int size() {
return size;
}
public Object get(int index) {
try{
return items[index];
} catch(IndexOutOfBoundsException e){
System.out.println("Exception Thrown: " + "Index is out of bound");
}
return index;
}
public boolean contains(Object obj) {
for (int j = 0; j < size; j++) {
if (obj.equals(this.get(j))) return true;
}
return false;
}
public void add(int index, Object obj) {
try{
if (size >= capacity) this.expand();
for (int j = size; j > index; j--) items[j] = items[j - 1];
items[index] = obj;
size++;
} catch(IndexOutOfBoundsException e){
System.out.println("Exception Thrown: " + "Index is out of bound");
}
return;
}
public int indexOf(Object obj) {
for (int j = 0; j < size; j++) {
if (obj.equals(this.get(j))) return j;
}
return -1;
}
public boolean remove(Object obj) {
for (int j = 0; j < size; j++) {
if (obj.equals(this.get(j))) {
for (int k = j; k < size-1; k++) items[k] = items[k + 1];
size--;
items[size] = null;
return true;
}
}
return false;
}
public Object remove(int index) {
try{
Object result = this.get(index);
for (int k = index; k < size-1; k++) items[k] = items[k + 1];
items[size] = null;
size--;
return result;
} catch(IndexOutOfBoundsException e){
System.out.println("Exception Thrown: " + "Index is out of bound");
}
return index;
}
public void set(int index, Object obj) {
try{
items[index] = obj;
} catch(IndexOutOfBoundsException e){
System.out.println("Exception Thrown: " + "Index is out of bound");
}
return;
}
public Iterator<E> iterator() {
return new MyIterator<E>();
}
public class MyIterator <T> implements Iterator<T>{
public boolean hasNext(){
}
public T next(){
}
public void remove(){
}
}
}
Basically I'm trying to improve the functionality of my arraylist, as it uses for loops for methods such as add and remove, however I am trying to use an iterator instead and I searched it up and I found out you cannot just simply add implements iterable to the main class, it has to be implemented by using three methods next(), hasNext() and remove(). I added the three methods at the bottom of the code but i'm really not sure how I implement it in order for it to begin to work.
You'll need to keep track of the index in the items array that the Iterator is on. Let's call it int currentIndex. hasNext() will return true if currentIndex < size. next() will increment currentIndex if hasNext() is true and return items[currentIndex], otherwise it should throw an Exception, say NoSuchElementException. Remove will call remove(currentIndex).
Here is an example (NOTE: I have not tried to compile this or anything so please update this post if you find any errors!)
public class MyArrayList<E> implements Iterable<E> {
...
#Override
public Iterator<E> iterator() {
return new Iterator<E>() {
private Object[] currentData = items;
private int pos = 0;
#Override
public boolean hasNext() {
return pos < currentData.length;
}
#Override
public E next() {
return (E) currentData[pos++];
}
#Override
public void remove() {
MyArrayList.this.remove(pos++);
}
};
}
}
You need to pass the items array to your MyIterator class so that you can keep track of the current position of the cursor in the array. Now based on the current position of the cursor you could implement all the abstract methods.
In the constructor of the MyIterator class pass the array as a parameter as public MyIterator(E[] array) and store the array as a local variable. also create a local variable cursor and set its value to 0.

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

Categories

Resources