JAVA如何检查数组参数

时间:2018-12-05 02:19:25

标签: java arraylist

我有2节课。一个叫做“发货”,另一个叫做“库存” 货件内部有一些变量,如下所示。

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 []数组元素之一

1 个答案:

答案 0 :(得分:0)

您可以使用this关键字来引用您的私有成员变量,并且仍然对传递给构造函数或函数的参数保持类似的命名约定。它使您的代码更容易为他人和您自己所理解=)。对于您传递给类的所有内容,都有两个单独的命名约定可能会造成很大的混乱。

我添加了一个主要功能来演示如何有效地操作这些类。

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());
    }

}

针对您的Inventory

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 +
                '}';
    }
}

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

从理论上讲,有很多方法可以完成此任务,但是我是通过制作一批货物来实现的,因此我可以制作filter来查找与您要添加的任何货物跟踪代码相同的代码。 / p>

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

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

在这里,我只是使该函数引发Exception,但是您可以在函数中在此处处理它,并记录您尝试添加相同批次的异常。在真实代码中,您不想破坏代码,因为您尝试添加重复的货件。您只想阻止它发生并继续前进!

针对您的Shipment

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”,以便您可以在该类之外访问跟踪代码。否则,它将保持私有状态,您将无法在需要检查重复的跟踪代码的此类之外进行比较。