java访问队列中对象的属性值
时间: 2024-05-05 16:19:26 浏览: 5
您可以使用Java中的队列类(例如LinkedList或ArrayDeque)来访问队列中的对象属性值。以下是一些基本示例代码:
1. 使用LinkedList类:
```java
LinkedList<Person> queue = new LinkedList<>();
queue.add(new Person("John", 25));
queue.add(new Person("Mary", 30));
queue.add(new Person("Peter", 40));
// 访问队列中第一个元素的属性
String firstName = queue.getFirst().getName();
int age = queue.getFirst().getAge();
System.out.println("First person in the queue is " + firstName + ", aged " + age);
```
2. 使用ArrayDeque类:
```java
ArrayDeque<Person> queue = new ArrayDeque<>();
queue.add(new Person("John", 25));
queue.add(new Person("Mary", 30));
queue.add(new Person("Peter", 40));
// 访问队列中最后一个元素的属性
String lastName = queue.getLast().getName();
int age = queue.getLast().getAge();
System.out.println("Last person in the queue is " + lastName + ", aged " + age);
```
其中,Person是一个自定义的类,具有name和age属性。请注意,您需要确保队列不为空(即在调用getFirst()或getLast()之前检查队列的大小)。