Java arraylist, пытаясь найти?
Это методы, которые мне дали, и все они недействительны. Я хочу получить доступ к результатам из displaySearchResults
используя соответствующий цикл, только чтение данных.
Кто-нибудь знает, что мне нужно сделать, чтобы получить результаты из 3 предыдущих методов поиска?
/**
* Searches inventory by model
* @param model is the model you'd like to find
*/
public void searchByModel(String model){
ArrayList<Vehicle> results = new ArrayList();
for(int i = 0; i < vehicles.size(); i++){
if(vehicles.get(i).getModel().equalsIgnoreCase(model)){
results.add(vehicles.get(i));
}
}
}
/**
* Searches inventory by year
* @param year is the year you'd like to find
*/
public void searchByYear(int year){
ArrayList<Vehicle> results = new ArrayList();
for(int i = 0; i < vehicles.size(); i++){
if(vehicles.get(i).getYear() == year){
results.add(vehicles.get(i));
}
}
}
/**
* Searches inventory by price
* @param minPrice is the lowest price you'd like to search by
* @param maxPrice is the highest price you'd like to search by
*/
public void searchByPrice(double minPrice, double maxPrice){
ArrayList<Vehicle> results = new ArrayList();
for(int i = 0; i < vehicles.size(); i++){
if(vehicles.get(i).getSellingPrice() < maxPrice &&
vehicles.get(i).getSellingPrice() > minPrice){
results.add(vehicles.get(i));
}
}
}
/**
* @return Displays search results, unsure of how to get this working still
*/
public void displaySearchResults(ArrayList<Vehicle> results){
for(Vehicle vehicle : results){
}
3 ответа
public void displaySearchResults(ArrayList<Vehicle> results){
for(Vehicle vehicle : results){
System.out.println(vehicle.getModel()+ " of " +vehicle.getYear()+ " of " + vehicle.getSellingPrice());
}
}
Вы можете сделать объект, который принимает в своем конструкторе массив транспортных средств и имеет элемент с именем results.
public class WhyWouldYouDoThis {
private List<Vehicle> results;
public WhyWouldYouDoThis() {
}
public List<Vehicle> getResults() {
return results;
}
/**
* Searches inventory by year
* @param year is the year you'd like to find
*/
public void searchByYear(int year){
results = new LinkedList<>();
for(int i = 0; i < vehicles.size(); i++){
if(vehicles.get(i).getYear() == year){
results.add(vehicles.get(i));
}
}
}
}
Теперь есть несколько вещей, которые нужно иметь в виду. А) Это довольно безумно, потому что ваши методы вам возвращают результат. Ваш текущий код действительно проблематичен на уровне API/ дизайна. Б) Это не потокобезопасно.
Измените методы поиска, чтобы они действительно возвращали результаты:
public List<Vehicle> searchByYear(int year){
ArrayList<Vehicle> results = new ArrayList<>();
for(int i = 0; i < vehicles.size(); i++){
if(vehicles.get(i).getYear() == year){
results.add(vehicles.get(i));
}
}
return results;
}
Теперь при отображении вы можете повторять результаты реального поиска:
public void displaySearchResults(ArrayList<Vehicle> results){
for(Vehicle vehicle : searchByYear(1991)){
//display whatever you want from it
}
// do this with the other results
}
Кроме того, если вы используете Java 8, вы можете заменить циклы for на более элегантные функциональные возможности:
public List<Vehicle> searchByPrice(double min, double max){
return vehicles.stream()
.filter(v -> (v.getSellingPrice() > min && v.getSellingPrice() < max))
.collect(Collectors.toList());
}