Cách sử dụng của hàm Stack vàQueues trong Java

Stack là kiểu chèn dữ liệu như khi trông sách. Quyển thứ nhất rồi chồng quyển thứ 2 nên rồi trồng quyển thứ 3 vv… Và khi muốn lấy thì phải lấy thì phải lấy thứ tự từ trên xuống lấy quyển 3 rồi lấy quyển 2 rồi mới lấy được quyển 1.

Còn Queues thì theo thứ tự xếp hàng ai đến trước thì được lấy trước.+

Hàm sự dùng:

add hoặc offer(E item): đẩy phần tử mới vào.

poll(): là lấy phần từ ra

package test.lession2;

import java.util.PriorityQueue;
import java.util.Stack;

public class StackAndQueues {
	public static void main(String[] args) {
//		Queues
		PriorityQueue<String> names = new PriorityQueue<String>();
		names.offer("A1");
		names.offer("C1");
		names.offer("A2");
		names.offer("B3");
		names.add("A");
		names.add("B");
		while (true) {
			String name = names.poll();
			if (name == null) {
				break;
			} else {
//				System.out.println("Name: " + name);
			}
		}

		// Stack
		Stack<String> books = new Stack<String>();
		books.push("VeuTo");
		books.push("ChanDai");
		books.push("MongTo");
		books.push("MatXinh");
//		book.forEach((list) -> {
//			System.out.println(list);
//		});

		for (int i = 0; i < books.size(); i++) {
			System.out.println(books.pop());
			System.out.println(books.pop());
		}
	}
}

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Chào mừng bạn đến với blog của tôi! Đây là nơi tôi chia sẻ những trải nghiệm, suy nghĩ và kiến thức mà tôi học được trong cuộc sống và công việc. Hy vọng bạn sẽ tìm thấy điều gì đó hữu ích và thú vị tại đây.

Design a site like this with WordPress.com
Get started