Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
33 kB
4
Indexable
Never
javacore.data

1. array
    1.1. Array.java

import java.util.Arrays;
import java.util.Scanner;

public class Array {
    private static int[] baseData = new int[10];

    public static void main(String[] args) {
        // myArray();

        sum();

        getInput();
        resizeArray();
        baseData[10] = 100;
        baseData[11] = 22;
        printArray(baseData);

        String[] array = {"b", "a", "g", "d"};

        java.util.Arrays.sort(array);

        Arrays.stream(array)
                .forEach(System.out::println);
    }

    public static void resizeArray() {
        int[] original = baseData;
        baseData = new int[12];
        for (int i = 0; i < original.length; i++) {
            baseData[i] = original[i];
        }
    }

    public static void getInput() {
        for (int i = 0; i < baseData.length; i++) {
            baseData[i] = i * 10;
        }
    }

    public static void myArray() {
        int[] myIntArray = new int[10];
        myIntArray[5] = 50;

        int[] myNumbers = {1, 2, 3, 4, 5};
        printArray(myNumbers);
    }

    public static void printArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.println("Element " + i + ": " + arr[i]);
        }
    }

    public static void sum() {
        Scanner scanner = new Scanner(System.in);
        int length = scanner.nextInt();
        int[] arr = new int[length];
        for (int i = 0; i < length; i++) {
            arr[i] = scanner.nextInt();
        }
        int n = scanner.nextInt();
        int sum = 0;
        for (int num : arr) {
            if (num > n) {
                sum += num;
            }
        }

        System.out.println(sum);
    }

}

####################################

    1.2. MultidimensionalArray.jva

import java.util.Arrays;
import java.util.Scanner;

public class MultidimensionalArray {

    public static void main(String[] args) {
        exercise3();
    }

    public static void exercise1() {
        Scanner scanner = new Scanner(System.in);

        int row = scanner.nextInt();
        int col = scanner.nextInt();
        int[][] arr = new int[row][col];

        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                arr[i][j] = scanner.nextInt();
            }
        }

        int c1 = scanner.nextInt();
        int c2 = scanner.nextInt();
        int temp = 0;
        if (c1 > c2) {
            temp = c1;
            c1 = c2;
            c2 = temp;
        }

        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (j == c1) {
                    temp = arr[i][c1];
                    arr[i][c1] = arr[i][c2];
                    arr[i][c2] = temp;
                }
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
    }

    public static void exercise2() {
        int[][] arrays = {{1, 2}, {0, 0}, {3, 4}};
        printCorners(arrays);
    }

    public static void printCorners(int[][] twoDimArray) {
        // write your code here

        System.out.print(twoDimArray[0][0] + " ");


        System.out.println(twoDimArray[0][twoDimArray[0].length - 1]);


        System.out.print(twoDimArray[twoDimArray.length - 1][0] + " ");


        System.out.println(twoDimArray[twoDimArray.length - 1][twoDimArray[twoDimArray.length - 1].length - 1]);


    }

    public static void exercise3() {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();

        int[][] arrays = new int[n][n];
        int[][] transposedArrays = new int[n][n];

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                arrays[i][j] = scanner.nextInt();
                transposedArrays[j][i] = arrays[i][j];
            }
        }

        System.out.println(Arrays.equals(arrays, transposedArrays)); // false

        boolean check = Arrays.deepEquals(arrays, transposedArrays); // true
        System.out.println(check? "YES" : "NO");
    }
}

##############################################

    1.3. Solution.java

public class Solution {
	public static void main(String[] args) {
		String[] cars = { "Volvo", "BMW", "Ford", "Mazda" };
		cars[0] = "Opel";
		System.out.println(cars[0]);
		for (int i = 0; i < cars.length; i++) {
			System.out.println(cars[i]);
		}
		
		int[] mNum = { 10, 20, 30, 40 };;
		System.out.println(mNum.length);
		
		int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
		System.out.println(myNumbers[1][2]);
		
		int[] num = new int[4];
	}
}

###############################################

    1.4. Varargs.java

/*
 * Passing arrays to methods
 * Mot method co the co tham so la mot array
 * Khi truyen mot gia tri kieu nguyen thuy vao method, mot ban sao cua gia tri se duoc tao
 * Khi truyen mot mang, mot ban sao reference se duoc tao, tuc la khi thay doi mang o trong method thi khi thoat khoi
 * method do, mang van se thay doi
 *
 * Varargs (variable-length arguments)
 * Vi du: int... number
 * co the xu ly tham so loai nay nhu mot mang thong thuong
 */

import java.util.Arrays;

public class Varargs {
    public static void main(String[] args) {
        int[] number = {1, 2, 3, 4, 5};
        swapFirstAndLastElements(number);
        System.out.println(Arrays.toString(number));

        printNumberOfArguments(1);
        printNumberOfArguments(1, 2, 3);
        printNumberOfArguments();
        printNumberOfArguments(new int[] {1, 2});

    }

    public static void inverseFlags(boolean[] flags) {
        // write your code here
        for (int i = 0; i < flags.length; i++) {
            flags[i] = !flags[i];
        }
    }

    public static void swapFirstAndLastElements(int[] nums) { // nums is an array
        if (nums.length < 1) {
            return; // it returns nothing, i.e. just exits the method
        }

        int temp = nums[nums.length - 1]; // save the last element in a temporary local variable
        nums[nums.length - 1] = nums[0];  // now, the last element becomes the first
        nums[0] = temp;                   // now, the first element becomes the former last
    }

    public static void printNumberOfArguments(int... numbers) {
        System.out.println(numbers.length);
    }
}

#########################################

2. collections
    2.1. queue
    2.2. deque
    2.3. example
        2.3.1. example1
            2.3.1.1. CollectionListMethod.java

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CollectionListMethod {
    public static void main(String[] args) {
        Theatre theatre = new Theatre("Olympian", 8, 12);
        List<Theatre.Seat> seatCopy = new ArrayList<>(theatre.seats);   // Shallow copy
        printList(seatCopy);

        Collections.reverse(seatCopy);
        Collections.shuffle(seatCopy);
        printList(seatCopy);
        printList(theatre.seats);

        Theatre.Seat minSeat = Collections.min(seatCopy);
        Theatre.Seat maxSeat = Collections.max(seatCopy);
        System.out.println("Min seat number is " + minSeat.getSeatNumber());
        System.out.println("Max seat number is " + maxSeat.getSeatNumber());
        System.out.println("=========================================================================================");

        sortList(seatCopy);
        printList(seatCopy);
    }

    public static void printList(List<Theatre.Seat> list) {
        for(Theatre.Seat seat : list) {
            System.out.print(" " + seat.getSeatNumber());
        }
        System.out.println();
        System.out.println("=========================================================================================");
    }

    public static void sortList(List<? extends Theatre.Seat> list) {
        for (int i = 0; i < list.size() - 1; i++) {
            for (int j = i + 1; j < list.size(); j++) {
                if (list.get(i).compareTo(list.get(j)) > 0) {
                    Collections.swap(list, i, j);
                }
            }
        }
    }
}

##################################

            2.3.1.2. Main.java

/*
 * Collection (Interface) bao gom: List, Set, Queue, Deque, Map
 * Chu y: Map khong truc tiep trien khai giao dien Collection
 */

public class Main {
    public static void main(String[] args) {
        Theatre theatre = new Theatre("Olympian", 8, 12);
        theatre.getSeats();
        theatre.reserveSeat("H11");


//        List<String> list = new ArrayList<>(Arrays.asList("Abc", "xyz"));
//        System.out.println(list);
//        list = new LinkedList<>();
    }
}

###################################

            2.3.1.3. Theatre.java

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Theatre {
    private final String theatreName;
    public List<Seat> seats = new ArrayList<>();

    public Theatre(String theatreName, int numRows, int seatsPerRow) {
        this.theatreName = theatreName;

        int lastRow = 'A' + (numRows - 1);
        for (char row = 'A'; row <= lastRow; row++) {
            for (int seatNum = 1; seatNum <= seatsPerRow; seatNum++) {
                Seat seat = new Seat(row + String.format("%02d", seatNum));
                seats.add(seat);
            }
        }
    }

    public String getTheatreName() {
        return theatreName;
    }

    public boolean reserveSeat(String seatNumber) {
        Seat requestedSeat = new Seat(seatNumber);
        int foundSeat = Collections.binarySearch(seats, requestedSeat, null);
        if (foundSeat >= 0) {
            return seats.get(foundSeat).reserve();
        } else {
            System.out.println("There is no seat " + seatNumber);
            return false;
        }
    }

    // for testing
    public void getSeats() {
        for (Seat seat : seats) {
            System.out.println(seat.getSeatNumber());
        }
    }

    public class Seat implements Comparable<Seat> {
        private final String seatNumber;
        private boolean reserved = false;

        private Seat(String seatNumber) {
            this.seatNumber = seatNumber;
        }

        public String getSeatNumber() {
            return seatNumber;
        }

        public boolean reserve() {
            if (!this.reserved) {
                this.reserved = true;
                System.out.println("Seat " + seatNumber + " reserved");
                return true;
            } else {
                return false;
            }
        }

        public boolean cancel() {
            if (this.reserved) {
                this.reserved = false;
                System.out.println("Reservation of seat " + seatNumber + " cancelled");
                return true;
            } else {
                return false;
            }
        }

        @Override
        public int compareTo(Seat seat) {
            return this.seatNumber.compareToIgnoreCase(seat.getSeatNumber());
        }
    }
}

##########################################

        2.3.2. example2
            2.3.2.1. ComparatorAndComparable

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ComparatorAndComparable {
    public static void main(String[] args) {
        Theatre theatre = new Theatre("Olympian", 8, 12);

        if (theatre.reserveSeat("D12")) {
            System.out.println("Please pay for D12");
        } else {
            System.out.println("Seat already reserved");
        }

        if (theatre.reserveSeat("B13")) {
            System.out.println("Please pay for B13");
        } else {
            System.out.println("Seat already reserved");
        }

        List<Theatre.Seat> reservedSeats = new ArrayList<>(theatre.getSeats());
        Collections.reverse(reservedSeats);
        printList(reservedSeats);

        List<Theatre.Seat> priceSeats = new ArrayList<>(theatre.getSeats());
        priceSeats.add(theatre.new Seat("B00", 13.00));
        priceSeats.add(theatre.new Seat("A00", 13.00));
        Collections.sort(priceSeats, Theatre.PRICE_ORDER);
        printList(priceSeats);
    }

    public static void printList(List<Theatre.Seat> list) {
        for(Theatre.Seat seat : list) {
            System.out.print(" " + seat.getSeatNumber() + " " + seat.getPrice());
        }
        System.out.println();
        System.out.println("=========================================================================================");
    }
}

#######################################

            2.3.2.2. Theatre.java

import java.util.*;

public class Theatre {
    private final String theatreName;
    private List<Seat> seats = new ArrayList<>();
    static final Comparator<Seat> PRICE_ORDER = new Comparator<Seat>() {
        @Override
        public int compare(Seat seat1, Seat seat2) {
            if (seat1.getPrice() < seat2.getPrice()) {
                return -1;
            } else if (seat1.getPrice() > seat2.getPrice()) {
                return 1;
            } else {
                return 0;
            }
        }
    };

    public Theatre(String theatreName, int numRows, int seatsPerRow) {
        this.theatreName = theatreName;

        int lastRow = 'A' + (numRows - 1);
        for (char row = 'A'; row <= lastRow; row++) {
            for (int seatNum = 1; seatNum <= seatsPerRow; seatNum++) {
                double price = 12.00;
                if ((row < 'D') && (seatNum >= 4 && seatNum <= 9)) {
                    price = 14.00;
                } else if ((row > 'F') || (seatNum < 4) || seatNum > 9) {
                    price = 7.00;
                }
                Seat seat = new Seat(row + String.format("%02d", seatNum), price);
                seats.add(seat);
            }
        }
    }

    public String getTheatreName() {
        return theatreName;
    }

    public boolean reserveSeat(String seatNumber) {
        Seat requestedSeat = new Seat(seatNumber);
        int foundSeat = Collections.binarySearch(seats, requestedSeat, null);
        if (foundSeat >= 0) {
            return seats.get(foundSeat).reserve();
        } else {
            System.out.println("There is no seat " + seatNumber);
            return false;
        }
    }

    // for testing
    public Collection<Seat> getSeats() {
        return seats;
    }

    public class Seat implements Comparable<Seat> {
        private final String seatNumber;
        private double price;
        private boolean reserved = false;

        private Seat(String seatNumber) {
            this.seatNumber = seatNumber;
        }

        Seat(String seatNumber, double price) {
            this.seatNumber = seatNumber;
            this.price = price;
        }

        public String getSeatNumber() {
            return seatNumber;
        }

        public double getPrice() {
            return price;
        }

        public boolean reserve() {
            if (!this.reserved) {
                this.reserved = true;
                System.out.println("Seat " + seatNumber + " reserved");
                return true;
            } else {
                return false;
            }
        }

        public boolean cancel() {
            if (this.reserved) {
                this.reserved = false;
                System.out.println("Reservation of seat " + seatNumber + " cancelled");
                return true;
            } else {
                return false;
            }
        }

        @Override
        public int compareTo(Seat seat) {
            return this.seatNumber.compareToIgnoreCase(seat.getSeatNumber());
        }
    }
}

#############################################

    2.4. list
        2.4.1. arraylist
            2.4.1.1. GroceryList.java

import java.util.ArrayList;

public class GroceryList {
    private static ArrayList<String> groceryList = new ArrayList<>();

    public ArrayList<String> getGroceryList() {
        return groceryList;
    }

    public void addGroceryItem(String item) {
        groceryList.add(item);
    }

    public void printGroceryList() {
        System.out.println("You have " + groceryList.size() + " items in your grocery list.");
        for (int i = 0; i < groceryList.size(); i++) {
            System.out.println((i + 1) + ". " + groceryList.get(i));
        }
    }

    public void modifyGroceryItem(String currentItem, String newItem) {
        int position = findItem(currentItem);
        if (position >= 0) {
            modifyGroceryItem(position, newItem);
        }
    }

    private void modifyGroceryItem(int position, String newItem) {
        groceryList.set(position, newItem);
        System.out.println("Grocery item " + (position + 1) + " has been modified.");
    }

    public void removeGroceryItem(String item) {
        int position = findItem(item);
        if (position >= 0) {
            removeGroceryItem(position);
        }
    }

    private void removeGroceryItem(int position) {
        String theItem = groceryList.get(position);
        groceryList.remove(position);
        System.out.println("Grocery item " + theItem + " has been removed.");
    }

    private int findItem(String searchItem) {
        return groceryList.indexOf(searchItem);
    }

    public boolean onFile(String searchItem) {
        int position = findItem(searchItem);
        return position >= 0;
    }
}

#################################################

            2.4.1.2. Main.java

import java.util.*;

/*
 *
 */

public class Main {
	private static Scanner scanner = new Scanner(System.in);
	private static GroceryList groceryList = new GroceryList();

	public static void main(String[] args) {
		//testArrayList();
		myIterator();
		// groceryListExercise();
	}

	public static void groceryListExercise() {
		boolean quit = false;
		int choice = 0;
		printInstructions();
		while (!quit) {
			System.out.println("Enter your choice: ");
			choice = scanner.nextInt();
			scanner.nextLine();

			switch (choice) {
				case 0 -> printInstructions();
				case 1 -> groceryList.printGroceryList();
				case 2 -> addItem();
				case 3 -> modifyItem();
				case 4 -> removeItem();
				case 5 -> searchForItem();
				case 6 -> processArrayList();
				case 7 -> quit = true;
				default -> {}
			}
		}
	}

	private static void processArrayList() {
		ArrayList<String> newArray = new ArrayList<>();
		newArray.addAll(groceryList.getGroceryList());

		// Cach khac
		ArrayList<String> nextArray = new ArrayList<>(groceryList.getGroceryList());

		String[] myArray = new String[groceryList.getGroceryList().size()];
		groceryList.getGroceryList().toArray(myArray);
	}

	private static void searchForItem() {
		System.out.print("Item to search for: ");
		String searchItem = scanner.nextLine();
		if (groceryList.onFile(searchItem)) {
			System.out.println("Found " + searchItem + " in our grocery list.");
		} else {
			System.out.println(searchItem + " is not in the shopping list.");
		}
	}

	private static void removeItem() {
		System.out.print("Enter item number: ");
		String removeItem = scanner.nextLine();
		scanner.nextLine();
		groceryList.removeGroceryItem(removeItem);
	}

	private static void modifyItem() {
		System.out.print("Enter item number: ");
		String curItem = scanner.nextLine();
		scanner.nextLine();
		System.out.print("Enter replacement item: ");
		String newItem = scanner.nextLine();
		groceryList.modifyGroceryItem(curItem, newItem);
	}

	private static void addItem() {
		System.out.print("Please enter the grocery item: ");
		groceryList.addGroceryItem(scanner.nextLine());
	}

	private static void printInstructions() {
		System.out.print("\nPress ");
		System.out.print("\n 0 - To print choice options.");
		System.out.print("\n 1 - To print the list of grocery item.");
		System.out.print("\n 2 - To add an item to the list.");
		System.out.print("\n 3 - To modify an item in the list.");
		System.out.print("\n 4 - To remove an item from the list.");
		System.out.print("\n 5 - To search for an item in the list.");
		System.out.print("\n 6 - .");
		System.out.print("\n 7 - To quit the application.\n");
	}

	public static void testArrayList() {
		ArrayList<String> cars = new ArrayList<>();
		cars.add("Volvo");
		cars.add("BMW");
		cars.add("Ford");
		cars.add("Mazda");
		System.out.println(cars);
		System.out.println(cars.get(2));
		cars.set(2, "Opel");
		System.out.println(cars);
		cars.remove(0);
		System.out.println(cars);
		System.out.println(cars.size());

		Collections.sort(cars);
		System.out.println(cars);

		ArrayList<Object> arr = new ArrayList<>();
		arr.add(1);
		arr.add("Thieu");
		arr.add(2.5);
		for (Object o : arr) {
			System.out.println(o);
		}

		ArrayList<String> names = new ArrayList<>(Arrays.asList("Thieu", "Hien", "Tung"));
	}

	public static void myIterator() {
		ArrayList<String> stringList = new ArrayList<>();
		stringList.add("A");
		stringList.add("B");
		stringList.add("C");
		stringList.add("D");
		stringList.add("E");
		Iterator<String> iterator = stringList.iterator();
		while ((iterator.hasNext())) {
			String letter = iterator.next();
			if (letter.equals("C")) {
				iterator.remove();
			}
		}

		for (String s : stringList) {
			System.out.println(s);
		}
	}
}

###############################################

        2.4.2. linkedlist
            2.4.2.1. Customer.java

public class Customer {
    private String name;
    private double balance;

    public Customer(String name, double balance) {
        this.name = name;
        this.balance = balance;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }
}

#########################################

            2.4.2.2. Demo.java

import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
import java.util.Scanner;

/*
 * Iterator va ListIterator deu co cach hoat dong va ham tuong tu nhau, nhung co nhung diem khac nhau:
 * - Iterator dung de duyet qua cac phan tu cua Collection, con ListIterator chi dung de duyet qua List
 * - Iterator chi co the duyet theo mot huong, con ListIterator co the duyet theo ca hai chieu, vi the no cung cap
 *   cac phuong thuc: hasPrevious(), previous(). Ngoai ra ListIterator con co phuong thuc set() de dat lai gia tri cua
 *   mot phan tu va phuong thuc add() de them phan tu.
 */

public class Demo {
    public static void main(String[] args) {
        test3();
    }

    public static void test1() {
        LinkedList<String> placesToVisit = new LinkedList<>();
        placesToVisit.add("Thai Binh");
        placesToVisit.add("Ha Noi");
        placesToVisit.add("Hai Phong");
        placesToVisit.add("Nam Dinh");
        placesToVisit.add("Hung Yen");
        placesToVisit.add("Ha Nam");

        printList(placesToVisit);

        placesToVisit.add(1, "Ninh Binh");
        printList(placesToVisit);

        placesToVisit.remove(4);
        printList(placesToVisit);

        placesToVisit.remove("Bac Ninh");
    }

    public static void test2() {
        LinkedList<String> placesToVisit = new LinkedList<>();
        placesToVisit.add("Thai Binh");
        placesToVisit.add("Ha Noi");
        placesToVisit.add("Hai Phong");
        placesToVisit.add("Nam Dinh");
        placesToVisit.add("Hung Yen");
        placesToVisit.add("Ha Nam");

        ListIterator<String> stringListIterator = placesToVisit.listIterator();
        while (stringListIterator.hasNext()) {
            String city = stringListIterator.next();
            if (city.equals("Hung Yen")) {
                stringListIterator.set("Bac Ninh");
                stringListIterator.add("Bac Giang");
            }
        }
        printList(placesToVisit);
    }

    public static void test3() {
        LinkedList<String> placesToVisit = new LinkedList<>();
        addInOrder(placesToVisit, "Thai Binh");
        addInOrder(placesToVisit, "Ha Noi");
        addInOrder(placesToVisit, "Phu Tho");
        addInOrder(placesToVisit, "Thai Nguyen");
        addInOrder(placesToVisit, "Ha Giang");
        addInOrder(placesToVisit, "Lai Chau");
        addInOrder(placesToVisit, "Son La");

        printList(placesToVisit);

        visit(placesToVisit);
    }

    private static void printList(LinkedList<String> linkedList) {
        Iterator<String> i = linkedList.iterator();
        while (i.hasNext()) {
            System.out.println("Now visiting " + i.next());
        }
        System.out.println("===========================");
    }

    private static boolean addInOrder(LinkedList<String> linkedList, String newCity) {
        ListIterator<String> stringListIterator = linkedList.listIterator();

        while (stringListIterator.hasNext()) {
            int comparison = stringListIterator.next().compareTo(newCity);
            if (comparison == 0) {
                // equal
                System.out.println(newCity + " is already included as a destination");
                return false;
            } else if (comparison > 0) {
                // new city should appear before this one
                stringListIterator.previous();
                stringListIterator.add(newCity);
                return true;
            } else if (comparison < 0) {
                // move on next city
            }
        }

        stringListIterator.add(newCity);
        return true;
    }

    private static void visit(LinkedList cities) {
        Scanner scanner = new Scanner(System.in);
        boolean quit = false;
        boolean goingForward = true;
        ListIterator<String> listIterator = cities.listIterator();

        if (cities.isEmpty()) {
            System.out.println("No cities in the itinerary");
        } else {
            System.out.println("Now visiting " + listIterator.next());
            printMenu();
        }

        while (!quit) {
            int action = scanner.nextInt();
            scanner.nextLine();
            switch (action) {
                case 0 -> {
                    System.out.println("Holiday (Vacation) over");
                    quit = true;
                }
                case 1 -> {
                    if (!goingForward) {
                        if (listIterator.hasNext()) {
                            listIterator.next();
                        }
                        goingForward = true;
                    }
                    if (listIterator.hasNext()) {
                        System.out.println("Now visiting " + listIterator.next());
                    } else {
                        System.out.println("Reached the end of the list");
                    }
                }
                case 2 -> {
                    if (goingForward) {
                        if (listIterator.hasPrevious()) {
                            listIterator.previous();
                        }
                        goingForward = false;
                    }
                    if (listIterator.hasPrevious()) {
                        System.out.println("Now visiting " + listIterator.previous());
                    } else {
                        System.out.println("We are at the start of the list");
                    }
                }
                case 3 -> printMenu();
            }
        }
    }

    private static void printMenu() {
        System.out.println("Available action:\nPress ");
        System.out.println("0 - to quit");
        System.out.println("1 - go to next city");
        System.out.println("2 - go to previous city");
        System.out.println("3 - print menu options");
    }
}

########################################################

            2.4.2.3. Main.java

import java.util.ArrayList;
import java.util.LinkedList;

public class Main {
	public static void main(String[] args) {
		testLinkedlist();
		exercise1();
	}

	public static void exercise1() {
		Customer customer = new Customer("Tim", 54.96);
		Customer anotherCustomer = customer; // anotherCustomer dang tro den customer
		anotherCustomer.setBalance(12.18);
		System.out.println("Balance for customer " + customer.getName() + " is " + customer.getBalance());

		ArrayList<Integer> intList = new ArrayList<>();

		intList.add(1);
		intList.add(3);
		intList.add(4);
		for (int i = 0; i < intList.size(); i++) {
			System.out.println(i + ": " + intList.get(i));
		}

		intList.add(1, 2);
		for (int i = 0; i < intList.size(); i++) {
			System.out.println(i + ": " + intList.get(i));
		}
	}

	public static void testLinkedlist() {
		LinkedList<String> cars = new LinkedList<>();
		cars.add("Volvo");
		cars.add("BMW");
		cars.add("Ford");
		cars.add("Mazda");
		System.out.println(cars);

		cars.addFirst("Abc");
		cars.addLast("Def");
		System.out.println(cars);
		cars.removeFirst();
		cars.removeLast();
		System.out.println(cars);

		System.out.println(cars.getFirst());
		System.out.println(cars.getLast());

		LinkedList<Object> myLinkedList = new LinkedList<>();
		myLinkedList.add(1);
		myLinkedList.add("Thieu");
		myLinkedList.add(2.3);
	}
}

###########################

    2.5. map
        2.5.1. linkedhashmap
        2.5.2. treemap
        2.5.3. hasmap
            2.5.3.1. Maps.java

import java.util.HashMap;
import java.util.Map;

/*
 * Map: key - value
 * key khong duoc trung, moi key se anh xa toi mot value duy nhat
 *
 * ham put() se tra ve gia tri value truoc do
 */

public class Maps {
    public static void main(String[] args) {
        Map<String, String> languages = new HashMap<>();
        languages.put("Java", "a compiled high level, object-oriented, platform independant language");
        languages.put("Python", "an interpreted, object-oriented, high level programming language with dynamic semantics");
        languages.put("Algol", "an algorithmic language");
        languages.put("BASIC", "Beginners All PURPOSES SYMBOLIC INSTRUCTION CODE");

        System.out.println(languages.put("Lisp", "Therein lies madness"));
        System.out.println(languages.get("Java"));

        System.out.println(languages.put("Java", "this is a Java course"));
        System.out.println(languages.get("Java"));

        if (languages.containsKey("Python")) {
            System.out.println("Python is already in the map");
        } else {
            System.out.println("I love Python");
        }

        System.out.println("======================================================================================");

        //languages.remove("Lisp");
        if (languages.remove("Algol", "a family of algorithmic languages")) {
            System.out.println("Algol Removed");
        } else {
            System.out.println("Algol not removed, key/value pair not found");
        }

        System.out.println(languages.replace("Scala", "this will not be added"));

        if (languages.replace("Lisp", "Therein lies madness",
                "a functional programming language with imperative features")) {
            System.out.println("Lisp replaced");
        } else {
            System.out.println("Lisp was not replaced");
        }

        System.out.println("======================================================================================");
        for (String key: languages.keySet()) {
            System.out.println(key + " : " + languages.get(key));
        }
    }
}

################################################

    2.6. set
        2.6.1. linkedhashset
        2.6.2. treeset
        2.6.3. hashset
            2.6.3.1. HeavenIyBody.java

import java.util.HashSet;
import java.util.Set;

public final class HeavenIyBody {
    private final String name;
    private final double orbitalPeriod;
    private final Set<HeavenIyBody> satellites;

    public HeavenIyBody(String name, double orbitalPeriod) {
        this.name = name;
        this.orbitalPeriod = orbitalPeriod;
        this.satellites = new HashSet<>();
    }

    public String getName() {
        return name;
    }

    public double getOrbitalPeriod() {
        return orbitalPeriod;
    }

    public boolean addMoon(HeavenIyBody moon) {
        return this.satellites.add(moon);
    }

    public Set<HeavenIyBody> getSatellites() {
        return new HashSet<>(this.satellites);
    }
}

##########################################

            2.6.3.2. SetAndHashSet.java

/*
 * set la tap hop khong co thu tu xac dinh va khong chua cac phan tu trung lap
 */

public class SetAndHashSet {
    private static Map<String, HeavenIyBody> solarSystem = new HashMap<>();
    private static HashSet<HeavenIyBody> planets = new HashSet<>();

    public static void main(String[] args) {
        HeavenIyBody abc = new HeavenIyBody("Thieu", 12);
        planets.add(abc);
        System.out.println(planets.contains(abc));

        TreeSet<Integer> set = new TreeSet<>();
        set.add(1);
        set.add(2);
        set.add(10);
        set.add(20);
        set.add(8);

        for(int i : set) {
            System.out.println(i);
        }


    }
}

#########################################




Leave a Comment