如何在创建使用 ArrayList 的对象期间设置 ArrayList 的数据类型

问题描述 投票:0回答:2

我有一个包含 ArrayList 的 Box 类对象。如何在创建 box1 对象时设置此 ArrayList 的数据类型?例如,box1 只能使用从 -50.0 到 50.0 的双精度值,box2 只能使用从 0 到 10 的整数,或者 box3 只能使用某些字符串。

import java.util.ArrayList;
public class Main {
    public static void main(String[] args) {
        Box box1 = new Box("box1");
        box1.addItem(5);
        box1.addItem(3.14);
        box1.addItem("String");
        System.out.println(box1.getItems());
    }
}

class Box {
    String boxName;
    ArrayList<Object> items = new ArrayList<>();

    Box(String boxName) {
    this.boxName = boxName;
    }

    public void addItem (Object item) {
        this.items.add(item);
    }

    public ArrayList getItems() {
        return this.items;
    }
}

我将 ArrayList 设置为对象数据类型,但这不太正确。 Box 类的每个对象都必须有一个具有单独数据类型和有效值列表的 ArrayList。

java oop arraylist types constructor
2个回答
0
投票

您可以使用 Java 泛型来指定 Box 类中 ArrayList 的数据类型

public class Box<T> {
    private ArrayList<T> items = new ArrayList<>();

    // Add an item to the box
    public void addItem(T item) {
        // You can add validation here to check the instance of the data type you want
        items.add(item);
    }

    public ArrayList<T> getItems() {
        return items;
    }
}

0
投票

您可以在代码中使用泛型来使用特定的类。 例如

class Box<T> {

    String boxName;
    List<T> items = new ArrayList<>();

    Box(String boxName) {
        this.boxName = boxName;
    }

    public void addItem (T item) {
        this.items.add(item);
    }

    public List<T> getItems() {
        return this.items;
    }
}

此外,要使用验证,您可以在类中添加新的

Predicate
字段。 例如

class Box<T> {

    String boxName;
    List<T> items = new ArrayList<>();
    Predicate<T> validator;

    Box(String boxName, Predicate<T> validator) {
        this.boxName = boxName;
    }

    public void addItem (T item) {
        if (validator.test(item)) {
            this.items.add(item);
        } else {
            // do nothing, throw exception, depends on your needs
        }
    }

    public List<T> getItems() {
        return this.items;
    }
}

然后你可以像这样创建你的类

new Box<Integer>("integerBox", item -> item >= 0 && item <= 10);
© www.soinside.com 2019 - 2024. All rights reserved.