Hey readers!
This time I’ll tell you about data structures in Java. Data structure is a special format for organizing and storing data.
What are they? just scroll down to find out 🙂
Array

Array is the simplest data structure in Java. There are types of array such as 2 dimentional array which you can learn on our previous post.
Learn more about array here.
ArrayList
ArrayList is dynamically resizing array, with ArrayList we don’t need to declare the number of array that we need. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed.

When the array hits its capacity, there’s a function that will make a new array which has double capacity.
There are some methods in ArrayList that we can use. Look at the codes below :
import java.util.ArrayList;
public class dataStructure {
public static void main(String[] args) {
// if you don't set the data type, all types of data is accepted so u can add string, integer n etc
ArrayList example = new ArrayList();
//if you want to set the array list only for integer data type, use <integer>
// ArrayList<Integer> example = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
// int a = (int) (Math.random()*100);
// example.add(a);
example.add(i);
}
// example.add(5,100) ---> INSERT 100 on index 5
example.add(5, 100);
// example.set(2,200) ---> REPLACE element on index 2 with 200
example.set(2,200);
//example.remove(6) ---> remove the index first, if none then the element is removed
example.remove(6);
//cuz int is primitive data type, we have to use integer to remove the object inside
example.remove(new Integer(100));
System.out.println("");
for (int i = 0; i < example.size(); i++) {
//example.size() is used to get the total element in ArrayList
//example.get(i) is used to get the value of i element ----> example[i]
System.out.println(example.get(i) +" ");
}
}
}
LinkedList

Linked List are linear data structures where the elements are not stored in contiguous locations and every element is a separate object with a data part and address part. The elements are linked using pointers and addresses.
Each element is known as a node which stores 2 things : value and next. *next is the reference of its neighbor memory address. The first element is called as head.

Unlike other data structures, linkedList has no index which cause it slower to search. But faster in inserts than array does.
here are the methods :
addFirst() is used to add new element at first position;
addLast() is used to add new element at last position;
Stack

Stack is a data structure physically similar to list but has restricted access to its elements. It allows acces only to its last item inserted.
The class is based on the basic principle Last – In – First – Out
There are some methods in stack :
push() = to add an item to stack, new item is automatically becomes the top item
pop() / pull() = to remove an item from stack, item which is removed commonly used outside the stack
peek() = to see the object on top of the stack
isEmpty() = it returns true if nothing is on the top of the stack. Else, returns false.
look at the codes below to understand better :
import java.util.Stack;
public class stack {
public static void main(String[] args) {
System.out.println("! STACK !");
Stack s = new Stack();
for (int i = 0; i < 10; i++) {
int a = (int) (Math.random() * 100);
System.out.println(a);
s.push(a); //inserts value to stack
}
System.out.println("==");
for (int i = 0; i < s.size(); i++) {
int item = Integer.parseInt(String.valueOf(s.pop()));
//parse int = change a value to integer
//string.value of = change any kind of data type to string
System.out.println(item);
//only half cause < s.size
}
// to show all data inside stack
while (!s.isEmpty()) {
int item = Integer.parseInt(String.valueOf(s.pop()));
System.out.println(item + " ");
}
}
}
Queue

The queue collection is used to hold the elements about to be processed and provides various operations like the insertion, removal etc. It is an ordered list of objects with its use limited to insert elements at the end of the list and deleting elements from the start of list i.e. it follows the FIFO or the First-In-First-Out principle.
Here are the methods :
enqueue() / push() = to add an item on queue, new item is at back
dequeue() / pull() = to remove an item on queue, item to be removed is the front one
Do you know twenty48 solitaire game?

You can make this game by using stack data structure ?
The output would be like this :

here is the code :
import java.util.Scanner;
import java.util.Stack;
public class AP_Week11_02060011810002 {
static Scanner scan = new Scanner(System.in);
static Stack A = new Stack();
static Stack B = new Stack();
static Stack C = new Stack();
static Stack D = new Stack();
static int number;
static int random;
static String vault;
static int score = 0;
static Stack card = new Stack();
static int trash = 0;
static int count = 0;
static void randomCard() {
for (int i = 0; i < 1000; i++) {
number = (int) Math.pow(2, ((int) (Math.random() * 6) + 1));
card.push(number);
}
}
static void start() {
System.out.println("====== TWENTY 48 SOLITAIRE =======");
System.out.println("==================================");
menu();
}
static void menu() {
System.out.println(" YOUR BOARD");
System.out.println("==================");
System.out.println("");
for (int i = 0; i < 4; i++) {
System.out.print("+-----+");
}
System.out.println("");
System.out.print("|");
if (!A.isEmpty()) {
vault = String.valueOf(A.peek());
for (int i = 0; i < (5 - vault.length()); i++) {
System.out.print(" ");
}
System.out.print(A.peek());
} else {
System.out.print(" - ");
}
System.out.print("|");
System.out.print("|");
if (!B.isEmpty()) {
vault = String.valueOf(B.peek());
for (int i = 0; i < (5 - vault.length()); i++) {
System.out.print(" ");
}
System.out.print(B.peek());
} else {
System.out.print(" - ");
}
System.out.print("|");
System.out.print("|");
if (!C.isEmpty()) {
vault = String.valueOf(C.peek());
for (int i = 0; i < (5 - vault.length()); i++) {
System.out.print(" ");
}
System.out.print(C.peek());
} else {
System.out.print(" - ");
}
System.out.print("|");
System.out.print("|");
if (!D.isEmpty()) {
vault = String.valueOf(D.peek());
for (int i = 0; i < (5 - vault.length()); i++) {
System.out.print(" ");
}
System.out.print(D.peek());
} else {
System.out.print(" - ");
}
System.out.print("|");
System.out.println("");
for (int i = 0; i < 4; i++) {
System.out.print("+-----+");
}
}
static void display() {
int current = (int) card.pop();
System.out.println("");
System.out.println("===========================================");
System.out.println("Current card : " + current + "| " + "Next Card : " + card.peek() + "| " + "Score : " + score);
System.out.println("===========================================");
card.push(current);
play();
}
static void play() {
System.out.print("Put card on 1 / 2 / 3 / 4 / 5 (trash) : ");
int answer = scan.nextInt();
boolean loop = true;
if (answer == 1) {
do {
check(A);
if (A.size() >= 1) {
if (A.size() <= 10) {
if ((int) A.peek() < (int) card.peek()) {
System.out.println("Your card shouldn't be greater than the card on the deck");
loop = false;
} else if ((int) A.peek() > (int) card.peek()) {
A.push(card.pop());
loop = true;
} else if ((int) A.peek() == (int) card.peek()) {
A.push(card.pop());
A = check(A);
loop = true;
} else {
System.out.println("Stack is full");
loop = false;
}
} else {
count += 1;
if (count == 5) {
lose();
}
}
} else {
A.push(card.pop());
loop = true;
}
} while (loop = false);
} else if (answer == 2) {
do {
check(B);
if (B.size() >= 1) {
if (B.size() <= 10) {
if ((int) B.peek() < (int) card.peek()) {
System.out.println("Your card shouldn't be greater than the card on the deck");
loop = false;
} else if ((int) B.peek() > (int) card.peek()) {
B.push(card.pop());
loop = true;
} else if ((int) B.peek() == (int) card.peek()) {
B.push(card.pop());
B = check(B);
loop = true;
} else {
System.out.println("Stack is full");
loop = false;
}
} else {
count += 1;
if (count == 5) {
lose();
}
}
} else {
B.push(card.pop());
loop = true;
}
} while (loop = false);
} else if (answer == 3) {
do {
check(C);
if (C.size() >= 1) {
if (C.size() <= 10) {
if ((int) C.peek() < (int) card.peek()) {
System.out.println("Your card shouldn't be greater than the card on the deck");
loop = false;
} else if ((int) C.peek() > (int) card.peek()) {
C.push(card.pop());
loop = true;
} else if ((int) C.peek() == (int) card.peek()) {
C.push(card.pop());
C = check(C);
loop = true;
} else {
System.out.println("Stack is full");
loop = false;
}
}else {
count += 1;
if (count == 5) {
lose();
}
}
} else {
C.push(card.pop());
loop = true;
}
} while (loop = false);
} else if (answer == 4) {
do {
check(D);
if (D.size() >= 1) {
if (D.size() <= 10) {
if ((int) D.peek() < (int) card.peek()) {
System.out.println("Your card shouldn't be greater than the card on the deck");
loop = false;
} else if ((int) D.peek() > (int) card.peek()) {
D.push(card.pop());
loop = true;
} else if ((int) D.peek() == (int) card.peek()) {
D.push(card.pop());
D = check(D);
loop = true;
} else {
System.out.println("Stack is full");
loop = false;
}
}else {
count += 1;
if (count == 5) {
lose();
}
}
} else {
D.push(card.pop());
loop = true;
}
} while (loop = false);
} else if (answer == 5) {
trash++;
if (trash > 2) {
System.out.println("Trash is full. Do you want to make space (Y/N) ?");
String trash = scan.next() + scan.nextLine();
if (trash.equalsIgnoreCase("Y")) {
score = score - 2;
card.pop();
}
} else {
card.pop();
}
} else {
System.out.println("==================================");
System.out.println(" G A M E O V E R ");
System.out.println("==================================");
System.exit(0);
}
menu();
display();
}
static Stack check(Stack z) {
if (z.size() >= 2) {
int checkNum = (int) z.pop();
int checkNum2 = (int) z.pop();
int total;
if (checkNum == checkNum2) {
total = checkNum + checkNum2;
score = score + total;
z.push(total);
return check(z);
} else {
z.push(checkNum2);
z.push(checkNum);
}
}
return z;
}
static void lose() {
System.out.println(" YOU LOSE");
System.out.println("==========");
}
static void win() {
System.out.println(" YOU WIN");
System.out.println("==========");
}
public static void main(String[] args) {
randomCard();
start();
display();
}
}
Thanks for visiting my site, don’t forget to smash the like button and leave a comment
Have a great day!
Self reflection :
for me, twenty48 wasn’t that easy to make it. I still need to pratice more using data structures.
Thanks to our lecturers and lecturer’s assistants for helping me.
src :
https://www.geeksforgeeks.org/arraylist-in-java/
http://www.codenuclear.com/how-arraylist-works-internally-java/
https://www.geeksforgeeks.org/linked-list-in-java/
https://introcs.cs.princeton.edu/java/43stack/