如何通过regNum更新ArrayList中Meter对象的workOrNot字段值?
doesNotWork Method in MeterArchive Hey there! Let's get that doesNotWork method sorted out— I spot the two issues tripping you up right away. Let's break them down and fix the code step by step.
The Two Key Issues
- Wrong string comparison: Using
==to checkregNumvalues compares object references, not the actual text content. In Java, you needequals()(orequalsIgnoreCase()for case-insensitive checks) to compare what the strings actually say. - Misusing
ArrayList.set(): You don't need to replace the entireMeterobject in the list. SinceMeteris a reference type, once you find the matching object, you can directly update itsworkOrNotfield—this change will automatically show up in the ArrayList, noset()required.
Correct Implementation
Here's how to rewrite the method properly, assuming your Meter class has getter/setter methods for regNum and workOrNot:
public class MeterArchive { private ArrayList<Meter> meters; // Your existing constructor and other methods here... public void doesNotWork(String regNum) { // Loop through each meter in the archive for (Meter meter : meters) { // Use equals() to compare registration numbers correctly if (meter.getRegNum().equals(regNum)) { // Directly update the workOrNot field of the matching meter meter.setWorkOrNot("No"); // If regNum is unique, we can exit the loop early to save time return; } } // Optional: Handle the case where no matching meter is found System.err.println("No meter found with registration number: " + regNum); } }
Quick Breakdown of the Fixes
String Comparison Done Right:
meter.getRegNum().equals(regNum)checks if the two strings have the same content, not just if they're the same object in memory. If your system allows case variations (like "XYZ789" vs "xyz789"), swap inequalsIgnoreCase()instead for more flexibility:if (meter.getRegNum().equalsIgnoreCase(regNum)) { // ... update the field ... }No Need for
ArrayList.set():
SinceMeteris a mutable object, when you pull it from the ArrayList and callmeter.setWorkOrNot("No"), you're modifying the exact same object that's stored in the list. There's no need to replace it—your change is already reflected in the archive.
For Context: When Would You Use ArrayList.set()?
Just to clarify, if you ever did need to replace the entire Meter object (which isn't necessary here), you'd do something like this—but it's redundant for your use case:
public void doesNotWorkAlternative(String regNum) { for (int i = 0; i < meters.size(); i++) { Meter meter = meters.get(i); if (meter.getRegNum().equals(regNum)) { meter.setWorkOrNot("No"); // Unnecessary here, but this is how you'd replace the object in the list meters.set(i, meter); return; } } }
Skip that extra set() call for your scenario—you're just doing extra work that doesn't add value.
内容的提问来源于stack exchange,提问作者Anders Lund

