Upload files to "OOP/Java/Lab/Week12"
This commit is contained in:
parent
2ae5d58f75
commit
100e80ccc3
5 changed files with 226 additions and 0 deletions
82
OOP/Java/Lab/Week12/GenStack.java
Normal file
82
OOP/Java/Lab/Week12/GenStack.java
Normal file
|
@ -0,0 +1,82 @@
|
|||
// 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());
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue