定义一个表示队列的泛型类Queue,分别对String对象和Integer对象执行入队列和出队列操作。
时间: 2024-05-15 11:18:29 浏览: 15
好的,这是一个使用Java语言定义Queue类的示例代码:
```
public class Queue<T> {
private List<T> elements;
public Queue() {
this.elements = new ArrayList<T>();
}
public void enqueue(T element) {
this.elements.add(element);
}
public T dequeue() {
if (this.elements.isEmpty()) {
return null;
}
return this.elements.remove(0);
}
}
```
在这个类中,使用泛型T来表示队列中的对象类型。我们可以使用enqueue方法将元素入队列,使用dequeue方法将队头元素出队列并返回。针对题目要求,我们可以分别创建一个String类型和一个Integer类型的Queue实例,并测试它们的入队列和出队列操作。
相关问题
定义一个泛型类MyQueue,实现队列的基本操作:add、remove、peek、isEmpty
。```java
public class MyQueue<T> {
private LinkedList<T> list;
public MyQueue() {
list = new LinkedList<T>();
}
public void add(T element) {
list.addLast(element);
}
public T remove() {
if (isEmpty()) {
throw new NoSuchElementException("Queue is empty.");
}
return list.removeFirst();
}
public T peek() {
if (isEmpty()) {
throw new NoSuchElementException("Queue is empty.");
}
return list.getFirst();
}
public boolean isEmpty() {
return list.isEmpty();
}
}
```
其中,LinkedList是Java集合框架中的一个双向链表实现,可以高效地支持队列的操作。泛型参数T表示队列中元素的类型,可以是任意类型。在构造函数中,创建一个空的LinkedList对象,表示一个空队列。add方法利用LinkedList的addLast方法实现入队操作;remove方法利用LinkedList的removeFirst方法实现出队操作,并在队列为空时抛出NoSuchElementException异常;peek方法利用LinkedList的getFirst方法获取队首元素,但不从队列中删除,也在队列为空时抛出NoSuchElementException异常;isEmpty方法利用LinkedList的isEmpty方法判断队列是否为空。
定义一个泛型类MyQueue,实现队列的基本操作:add、remove、peek、isEmpty。
好的,你的问题是关于泛型类的实现。以下是MyQueue类的代码示例:
```java
public class MyQueue<E> {
private LinkedList<E> list = new LinkedList<E>();
public void add(E element) {
list.addLast(element);
}
public E remove() {
if (list.isEmpty()) {
throw new NoSuchElementException();
}
return list.removeFirst();
}
public E peek() {
if (list.isEmpty()) {
throw new NoSuchElementException();
}
return list.getFirst();
}
public boolean isEmpty() {
return list.isEmpty();
}
}
```
这个类使用了Java集合框架中的LinkedList作为内部存储结构,通过泛型E实现了可以存储任意类型的元素。add方法在队列尾部加入一个元素,remove方法从队列头部移除一个元素并返回,peek方法只返回队列头部元素但不移除,isEmpty方法判断队列是否为空。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)