我有一个名为anItem的类,它允许我将变量建模到一个对象中。
我有很多这些对象,我想将它们放入一个集合中。该集合的类代码是什么?
这就是我所拥有的:
package com.rest.myproject;
public class anItem
{
String name;
String age;
public anItem()
{
super();
}
//methods
public String getName()
{
return this.name;
}
public void setName(String newName)
{
this.name=newName;
}
public String getAge()
{
return this.age;
}
public void setAge(String newAge)
{
this.age=newAge;
}
}
Public class aCollectionOfItems
{
anItem[] item; ->should I create a array of items to add and remove from?
public aCollection()
{
super();
}
//How do I add aItem to my collection, create an array of items?
}
答案 0 :(得分:2)
使用List
来保留您的商品。
public class Item {
private String name;
private String age;
//methods
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return this.age;
}
public void setAge(String age) {
this.age = age;
}
}
public class CollectionOfItems {
List<Item> items = new ArrayList<>();
public void addItem(Item item) {
items.add(item);
}
}
答案 1 :(得分:1)
public class CollectionOfItems {
int size = 10; //any size that is required.
private final Item[] item;
public aCollection(){
super();
item = new Item[size];
}
}
Java Collections也可用于保存项目,以替代Arrays。
答案 2 :(得分:0)
我建议您阅读Oracle的Java集合文档/教程: https://docs.oracle.com/javase/tutorial/collections/
一些简短的例子: