Abstract Data Types (ADT)

This page is under construction. Please come back later.
/******************************************************************************
* This program demonstrates the Stack ADT
*
* Copyright © 2021 Richard Lesh. All rights reserved.
*****************************************************************************/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.pureprogrammer.Utils;
public class ADTStack {
static class IntegerStack {
// Internal representation for the stack is a list
private List<Integer> stack = new ArrayList<>();
public IntegerStack() {
stack = new ArrayList<>();
}
public int pop() throws RuntimeException {
if (stack.size() == 0) {
throw new RuntimeException("Can't pop on empty stack!");
}
return stack.remove(stack.size() - 1);
}
public void push(int value) {
stack.add(value);
}
public int peek() throws RuntimeException {
if (stack.size() == 0) {
throw new RuntimeException("Can't peek on empty stack!");
}
return stack.get(stack.size() - 1);
}
}
public static void main(String[] args) {
IntegerStack stack = new IntegerStack();
for (int x = 1; x <= 10; ++x) {
stack.push(x);
}
try {
System.out.println(stack.peek());
for (int x = 1; x <= 11; ++x) {
System.out.println(stack.pop());
}
} catch (RuntimeException ex) {
System.out.println(Utils.exceptionMessage(ex));
} catch (Exception ex) {
System.out.println("Unknown Exception!");
}
}
}
Output
$ javac -Xlint ADTStack.java
$ java -ea ADTStack
10
10
9
8
7
6
5
4
3
2
1
RuntimeException: Can't pop on empty stack!
/******************************************************************************
* Simple first program.
*
* Copyright © 2020 Richard Lesh. All rights reserved.
*****************************************************************************/
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
Output
$ javac -Xlint HelloWorld.java
$ java -ea HelloWorld
Hello, world!
/******************************************************************************
* Simple first program.
*
* Copyright © 2020 Richard Lesh. All rights reserved.
*****************************************************************************/
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
Output
$ javac -Xlint HelloWorld.java
$ java -ea HelloWorld
Hello, world!
Questions
Projects
More ★'s indicate higher difficulty level.
References
- [[Java Language Specification]], Java SE 21 Edition, Gosling, et. al., 2023.
- [[Java Tutorials]]
- [[Java at TutorialsPoint]]
- Download Java at [[Amazon Corretto]], [[Azul Zulu]], [[Eclipse Temurin]] or [[Oracle JDK]]
Pure Programmer


