创建一个类Queue代表队列(先进先出),添加add(Object obj) 及get()方法, 并添加main()方法进行验证 思路: 使用LinkedList实现队列,在向LinkedList中添加时,使用addFirst()方法, 在从LinkedLsit中取出时,使用removeLast()方法
1 package com.lch.book3chapter1.exercise4; 2 3 import java.util.LinkedList; 4 5 6 public class QueueTest { 7 8 9 public static void main(String[] args) { 10 Student stu1 = new Student("李磊", 90); 11 Student stu2 = new Student("韩梅", 96); 12 Student stu3 = new Student("李中", 79); 13 14 Queue<Student> q = new Queue<Student>(); 15 q.add(stu1); 16 q.add(stu2); 17 q.add(stu3); 18 for (int i = 0; i < q.size(); i++) { 19 Student s = q.get(); 20 System.out.println(s.getName() + "-" + s.getScore()); 21 } 22 } 23 24 } 25 26 class Queue<T> { 27 private LinkedList<T> list = null; 28 int count = 0; 29 30 public Queue() { 31 list = new LinkedList<T>(); 32 } 33 34 public T get() { 35 T obj = null; 36 if (!list.isEmpty()) { 37 // 第一个添加的元素在队列的尾部 38 obj = list.removeLast(); // 删除并返回列表的最后一个元素(第一个被添加的元素) 39 } 40 return obj; 41 // return list.getLast(); //没有删除操作,获取到的永远是最后一个 42 } 43 44 public void add(T obj) { 45 list.addFirst(obj); 46 this.count++; 47 } 48 49 public int size() { 50 return count; 51 } 52 } 53 54 class Student { 55 private String name; 56 private int score; 57 58 public Student(String name, int score) { 59 super(); 60 this.name = name; 61 this.score = score; 62 } 63 64 public String getName() { 65 return name; 66 } 67 68 public void setName(String name) { 69 this.name = name; 70 } 71 72 public int getScore() { 73 return score; 74 } 75 76 public void setScore(int score) { 77 this.score = score; 78 } 79 80 @Override 81 public String toString() { 82 return "Student [name=" + name + ", score=" + score + "]"; 83 } 84 85 86 }
打印结果
原文:https://www.cnblogs.com/enjoyjava/p/9321166.html