MIT-Curricular/OOP/Java/Lab/Week12/GenStack.java

83 lines
1.8 KiB
Java
Raw Permalink Normal View History

2024-10-26 02:14:18 +05:30
// Generic Stack class
class Stack<T> {
private Object[] elements;
private int top;
private static final int DEFAULT_SIZE = 10;
public Stack() {
elements = new Object[DEFAULT_SIZE];
top = -1;
}
public void push(T item) {
elements[++top] = item;
}
public T pop() {
if (isEmpty()) return null;
return (T) elements[top--];
}
public boolean isEmpty() {
return top == -1;
}
}
// Student class
class Student {
private String name;
private int id;
public Student(String name, int id) {
this.name = name;
this.id = id;
}
public String toString() {
return "Student [name=" + name + ", id=" + id + "]";
}
}
// Employee class
class Employee {
private String name;
private String department;
public Employee(String name, String department) {
this.name = name;
this.department = department;
}
public String toString() {
return "Employee [name=" + name + ", department=" + department + "]";
}
}
public class Main {
public static void main(String[] args) {
// Stack of Students
Stack<Student> studentStack = new Stack<>();
studentStack.push(new Student("John", 101));
studentStack.push(new Student("Mary", 102));
System.out.println("Students popped from stack:");
while (!studentStack.isEmpty()) {
System.out.println(studentStack.pop());
}
// Stack of Employees
Stack<Employee> employeeStack = new Stack<>();
employeeStack.push(new Employee("Bob", "IT"));
employeeStack.push(new Employee("Alice", "HR"));
System.out.println("\nEmployees popped from stack:");
while (!employeeStack.isEmpty()) {
System.out.println(employeeStack.pop());
}
}
}