将项目添加到 ArrayList 与分离

Adding items to ArrayList with separation

我正在做一个使用 ArrayLists 进行网络抓取的项目。当我抓取信息时,它返回为 item [0] = pencilitem [1] = .50。我希望这些项目放在一起,或者如果可能的话,如果价格和项目每个都有自己的 ID 会更好,但每个项目都以某种方式链接在一起,这样我就可以分别引用每个项目。此外,有时在抓取时我会得到 item [2] = paperitem [3] = .00item [4] = wide bound college ruled,其中 item [4] 表示包含在需要包含在 ArrayList 中的项目中的可选描述或者像以前一样在一个单独的由 ids 链接的 ArrayList 中。任何想法表示赞赏。

最好为您的名称、价格和描述制作一个 class 项目宽度变量。

然后你可以创建一个 ArrayList 来存储你所有的项目。

如果您只需要名称和价格,最好的解决方案是使用 Map,它的工作方式有点像 ArrayList,但您有一对 而不是单个元素,像 。 如果您需要两个以上的值,我建议您创建自己的 class,例如:

   public class Item {
       private String name;
       private double price;
       private String description;
   }

使用您需要的所有额外方法,然后像这样声明您的 ArrayList;

 ArrayList<Item> items = new ArrayList<>()

您应该将对象建模为 class,例如 "item",并将每个值添加为 class 的变量。例如:

public class item{

    private String name;
    private double price;
    private String description; //If there's no description it could be null

    // Constructor
    ...

    // Getters and setters
   ...
}

您需要将价格格式化为双精度。