import java.util.ArrayList; public class Stack<E extends Number> { private ArrayList<E> list; public Stack(ArrayList<E> list) { this.list = list; } public void push(E element) { list.add(element); } public E pop() { if (list.isEmpty()) { throw new IllegalStateException("Stack is empty"); } return list.remove(list.size() - 1); } public int size() { return list.size(); } public double average() { if (list.isEmpty()) { return 0.0; } double sum = 0.0; for (E element : list) { sum += element.doubleValue(); } return sum / list.size(); } public boolean compareAverage(Stack<? extends Number> other) { return Double.compare(this.average(), other.average()) == 0; } public static void main(String[] args) { Stack<Integer> s1 = new Stack<>(new ArrayList<>()); s1.push(1); s1.push(2); s1.push(3); s1.push(4); s1.push(5); System.out.println("Integer stack average: " + s1.average()); Stack<Double> s2 = new Stack<>(new ArrayList<>()); s2.push(1.1); s2.push(2.2); s2.push(3.3); s2.push(4.4); s2.push(5.5); System.out.println("Double stack average: " + s2.average()); System.out.println("Same average? " + s1.compareAverage(s2)); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter