stack using generics

PHOTO EMBED

Wed May 29 2024 09:39:15 GMT+0000 (Coordinated Universal Time)

Saved by @signup

import java.util.*;

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() {
        E v = list.get(list.size() - 1);
        list.remove(list.size() - 1);
        return v;
    }

    public double avg() {
        int len = list.size();
        double sum = 0.0;
        for (E item : list) {
            sum += item.doubleValue();
        }
        return sum / len;
    }

    public boolean compareAvg(Stack<E> s) {
        return this.avg() == s.avg();
    }

    public static void main(String[] args) {
        ArrayList<Integer> intList = new ArrayList<>();
        Stack<Integer> s1 = new Stack<>(intList);
        s1.push(1);
        s1.push(2);
        s1.push(3);
        s1.push(4);
        System.out.println("Integer average: " + s1.avg());

        ArrayList<Double> doubleList = new ArrayList<>();
        Stack<Double> s2 = new Stack<>(doubleList);
        s2.push(1.1);
        s2.push(2.2);
        s2.push(3.3);
        s2.push(4.4);
        System.out.println("Double average: " + s2.avg());

        // Create another stack with the same type
        Stack<Integer> s3 = new Stack<>(new ArrayList<>());
        s3.push(5);
        s3.push(6);
        s3.push(7);
        s3.push(8);
        System.out.println("Are averages same: " + s1.compareAvg(s3));
    }
}
content_copyCOPY