( 1 )编写HeadPhone (耳机)类,包含brand (品牌)和price属性,该类实现Comparable接口规定该类对象大小,即手机按照价格来排序。( 2 )创建一个只可以放HeadPhonee类的链表,链表当中添加3个HeadPhone对象,依次次遍历每个对象.并在屏墓卜输出排序前链去中的数据.( 3 )调用Collections的sort0方法将链表当中的对象按price值排序;并在屏幕上输出排序后链表中的数据;( 4 )调用Collections的binarySearch ( )方法,查找当前对象的price的值是否和链表当中的某一个对象的price的值相同,若有,屏幕上输出对应的下标值;
时间: 2024-03-26 19:36:08 浏览: 77
Headphone-Jack-to-Arduino:通过耳机插Kong和 Arduino 从智能手机触发相机闪光灯
好的,以下是对您的问题的回答:
(1) HeadPhone类实现如下:
```java
public class HeadPhone implements Comparable<HeadPhone>{
private String brand;
private double price;
public HeadPhone(String brand, double price){
this.brand = brand;
this.price = price;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public int compareTo(HeadPhone o) {
if (this.price > o.getPrice()){
return 1;
}else if (this.price < o.getPrice()){
return -1;
}else{
return 0;
}
}
}
```
(2) 创建只能放HeadPhone类的链表,并添加3个对象,遍历并输出排序前链表中的数据:
```java
public static void main(String[] args) {
List<HeadPhone> headPhoneList = new LinkedList<>();
headPhoneList.add(new HeadPhone("Sony", 99.99));
headPhoneList.add(new HeadPhone("Bose", 199.99));
headPhoneList.add(new HeadPhone("Sennheiser", 149.99));
System.out.println("排序前链表中的数据:");
for (HeadPhone headPhone : headPhoneList) {
System.out.println(headPhone.getBrand() + ": " + headPhone.getPrice());
}
}
```
输出结果为:
```
排序前链表中的数据:
Sony: 99.99
Bose: 199.99
Sennheiser: 149.99
```
(3) 使用Collections的sort方法对链表中的对象按price值排序,并输出排序后链表中的数据:
```java
Collections.sort(headPhoneList);
System.out.println("排序后链表中的数据:");
for (HeadPhone headPhone : headPhoneList) {
System.out.println(headPhone.getBrand() + ": " + headPhone.getPrice());
}
```
输出结果为:
```
排序后链表中的数据:
Sony: 99.99
Sennheiser: 149.99
Bose: 199.99
```
(4) 使用Collections的binarySearch方法查找当前对象的price值是否和链表中的某一个对象的price值相同,若有,输出对应的下标值:
```java
double priceToSearch = 149.99;
int index = Collections.binarySearch(headPhoneList, new HeadPhone("", priceToSearch));
if (index >= 0){
System.out.println("价格为" + priceToSearch + "的耳机在链表中的下标为:" + index);
}else{
System.out.println("价格为" + priceToSearch + "的耳机不在链表中。");
}
```
输出结果为:
```
价格为149.99的耳机在链表中的下标为:1
```
阅读全文