JAVA如何检查数组参数

标签 java arraylist

我有两个类。一个名为“发货”,另一个名为“库存” 在 cargo 内部,有一些变量如下。

public class Shipment
{
private int trackingCode;
private int priority;
private double shippingPrice;
private double weight;
private String originCity;
private String destCity;
private String trackingPage;

我创建了如下的“库存”

public class Inventory
{

private ArrayList<Shipment> packages;

public Inventory(Shipment[] listOfPackage)
{
    if(listOfPackage == null){
        throw new IllegalArgumentException("List of Packages cannot be null.");
    }

    packages = new ArrayList<Shipment>(Arrays.asList(listOfPackage));  

}

现在我的问题是如何创建一个方法来将新包添加到ArrayList,并且不允许重复的跟踪代码需要抛出异常。

public ArrayList<Package> addPackage()

我很困惑如何进行重复的跟踪代码检查,因为它是 Shipment[] 数组元素之一

最佳答案

您可以使用 this 关键字来引用您的私有(private)成员变量,并且仍然为传递到构造函数或函数的参数保留类似的命名约定。它使您的代码对其他人和您自己来说更容易理解 =)。对于传递到类中的所有内容有两个单独的命名约定可能会变得非常困惑。

我添加了一个 main 函数来演示如何有效地操作这些类。

public class Application {

    public static void main(String[] args) {

        // define some unique shipments
        Shipment a = new Shipment(1,1, 10.0, 20.3, "Denver", "Seattle", "xyz");
        Shipment b = new Shipment(2,9, 45.88, 130.1, "Denver", "Los Angeles", "xyz");
        Shipment c = new Shipment(3,3, 14.67, 6.8, "Houston", "Dallas", "xyz");
        Shipment d = new Shipment(1,4, 12.99, 2.3, "New York", "London", "xyz");

        // populate your inventory with an array of initial shipments "a", "b", and "c"
        Shipment[] initialShipments = new Shipment[] { a, b, c };
        Inventory inventory = new Inventory(initialShipments);

        // print the inventory before adding the new shipment
        System.out.println(inventory.toString());

        // add shipment "d" to your inventory with the new method
        try {
            inventory.addShipment(d);
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
        }

        // print the inventory after adding the new shipment
        System.out.println(inventory.toString());
    }

}

对于您的库存:

public class Inventory {

    private ArrayList<Shipment> shipments;

    public Inventory(Shipment[] shipments) {
        if(shipments == null) {
            throw new IllegalArgumentException("List of shipments cannot be null.");
        }
        this.shipments = new ArrayList<>(Arrays.asList(shipments));
    }

    public void addShipment(Shipment shipment) throws Exception {

        Optional<Shipment> duplicateShipment = shipments
                .stream()
                .filter(otherShipment -> otherShipment.getTrackingCode() == shipment.getTrackingCode())
                .findAny();

        if(duplicateShipment.isPresent()) {
            String errorMessage = MessageFormat.format(
                    "A shipment with tracking code {0} already exists in this inventory.",
                    shipment.getTrackingCode()
            );
            throw new Exception(errorMessage);
        }
        else {
            this.shipments.add(shipment);
        }
    }

    @Override
    public String toString() {
        return "Inventory{" +
                "shipments=" + shipments +
                '}';
    }
}

为了检查重复的跟踪代码,您必须对现有货件进行流式处理,以便您可以在这些货件中查找与您尝试添加的跟踪代码相匹配的跟踪代码。

理论上有很多方法可以实现这一点,但我通过创建您的货件流来实现这一点,这样我就可以创建一个过滤器来查找与您添加的货件跟踪代码相同的任何货件跟踪代码。

此流末尾的 findAny 仅返回一个 Optional,这意味着它可能会返回某些内容,也可能不返回某些内容。

对于Optional类型,您可以使用isPresent()函数测试是否发现重复项。如果存在重复项,您可以根据需要引发异常。

这里我只是让函数抛出异常,但您可以在函数中处理它,并仅记录您尝试添加相同的货件。在实际代码中,您不希望代码因为尝试添加重复的货件而被破坏。您只想阻止它发生并继续前进!

对于您的货件:

public class Shipment {
    private int trackingCode;
    private int priority;
    private double shippingPrice;
    private double weight;
    private String originCity;
    private String destCity;
    private String trackingPage;

    public Shipment(int trackingCode, int priority, double shippingPrice, double weight, String originCity, String destCity, String trackingPage) {
        this.trackingCode = trackingCode;
        this.priority = priority;
        this.shippingPrice = shippingPrice;
        this.weight = weight;
        this.originCity = originCity;
        this.destCity = destCity;
        this.trackingPage = trackingPage;
    }

    public int getTrackingCode() {
        return trackingCode;
    }
}

您需要向 Shipment 类添加一个“getter”,以便您可以访问该类之外的跟踪代码;否则,它将保持私有(private)状态,并且您将无法在需要检查重复跟踪代码的此类之外进行比较。

关于JAVA如何检查数组参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53624223/

相关文章:

java - 在查询、jpa 存储库和 spring boot 中使用非硬编码值

java - 始终为同一客户创建 QuickBooks Online Java SDK 发票

Java ArrayList get() 作为整数而不是对象

ReactJs - 网格数据数组

java - 排除基于 PropertyFileConfig 的 CDI Bean(DeltaSpike,WebSphere 8.5.5)

java - URLConnection 有时返回空字符串响应?

java - 如何不断更新日期/日历对象?

java - 从 Arraylist 动态创建的单选按钮

java - 如何将ArrayList传递到本地数据库

java - 当对象放入 ArrayList 时对其进行排序