Java静态方法实现:从含Fruit、Ball对象的混合ArrayList中取最低价元素
Hey there! Let's work through this problem together. The core challenge here is handling two different types (Fruit and Ball) that share a common Price property—we need a way to treat them uniformly when searching for the minimum price.
Step 1: Define a Common Interface
First, create an interface that both classes can implement. This gives us a consistent way to access the Price property regardless of the object type:
public interface HasPrice { // Adjust return type to int/BigDecimal if your Price uses that type double getPrice(); }
Then update your Fruit and Ball classes to implement this interface:
public class Fruit implements HasPrice { private double price; // Constructor, getters, setters public Fruit(double price) { this.price = price; } @Override public double getPrice() { return price; } } public class Ball implements HasPrice { private double price; public Ball(double price) { this.price = price; } @Override public double getPrice() { return price; } }
Step 2: Write the Static Method to Find the Minimum Price Element
Now we can create a static method that handles a collection of HasPrice objects. Here are two solid approaches:
Option 1: Traditional Loop (Great for clarity)
import java.util.ArrayList; import java.util.Collection; public class PriceFinder { public static HasPrice findLowestPricedElement(Collection<HasPrice> items) { if (items == null || items.isEmpty()) { // Choose to return null or throw an exception based on your needs throw new IllegalArgumentException("Collection can't be null or empty"); } HasPrice lowestItem = null; double lowestPrice = Double.MAX_VALUE; for (HasPrice item : items) { if (item.getPrice() < lowestPrice) { lowestPrice = item.getPrice(); lowestItem = item; } } return lowestItem; } }
Option 2: Java Streams (Concise & Modern)
If you're using Java 8+, streams make this even cleaner:
import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.Optional; public class PriceFinder { public static HasPrice findLowestPricedElement(Collection<HasPrice> items) { if (items == null) { throw new IllegalArgumentException("Collection can't be null"); } return items.stream() .min(Comparator.comparingDouble(HasPrice::getPrice)) .orElseThrow(() -> new IllegalArgumentException("Collection can't be empty")); } }
Step 3: Test the Method
Here's how you'd use this with your existing objects:
public class Main { public static void main(String[] args) { ArrayList<HasPrice> mixedItems = new ArrayList<>(); mixedItems.add(new Fruit(1.99)); mixedItems.add(new Fruit(0.99)); mixedItems.add(new Fruit(2.49)); mixedItems.add(new Ball(3.99)); mixedItems.add(new Ball(1.49)); mixedItems.add(new Ball(0.79)); HasPrice cheapestItem = PriceFinder.findLowestPricedElement(mixedItems); System.out.println("Cheapest item price: " + cheapestItem.getPrice()); // Check the type if needed if (cheapestItem instanceof Ball) { System.out.println("It's a Ball!"); } else if (cheapestItem instanceof Fruit) { System.out.println("It's a Fruit!"); } } }
Key Notes
- Edge Cases: Always validate for
nullor empty collections to avoid runtime crashes. Pick between returningnullor throwing an exception based on your app's requirements. - Type Safety: The
HasPriceinterface ensures we only process objects with a validPriceproperty, preventingClassCastExceptions. - Flexibility: This setup works for any future classes that implement
HasPrice—no need to modify thefindLowestPricedElementmethod later.
内容的提问来源于stack exchange,提问作者Dummy

