So I want to output the max PRICE of a List.
Now I need the i-1 element of the for loop to get the index and then print it as a List how should it be ?
I have some exprience in C# where I think this works there but in Java it doesnt. :/
CodePudding user response:
Java does not support overwriting operators, so BookList1[i-1]
is not allowed, because BookList1
is not an array. You need to use BookList1.get(i-1)
to get the element on that index. In C# you are allowed to use BookList1[i]
, because C# lists implement this operator. This was already introduced in C , but never im Java.
CodePudding user response:
You can use the following approach to get most expensive:
public void getMostExpensive (List<Book> bookList){
Book expensive = bookList.get(0);
for (Book book : bookList) {
if(book.getPrice() > expensive.getPrice())
expensive = book;
}
System.out.println(expensive.getPrice());
}