我只是想检查ArrayList是否为空,所以我查看了Java库,发现Java中有一个isEmpty方法可以为我执行此操作,但是我的代码无法在此处编译。一直说找不到方法。我没有在代码中定义该方法,但我认为不必这样做,因为它是Java定义的方法,并且我已经导入了java.util.ArrayList。如果不再使用此方法,还有其他方法可以检查ArrayList是否为空吗?
else if((userChoice.equals("S")) || (userChoice.equals("s"))){
boolean empty = this.cat.isEmpty();
if (empty == true){
System.out.println("there is nothing i this catalog");
}
else{
this.cat.printList();
}
}
这是我在叫它的猫
this.name = name;
this.cat = new Catalog();
//CREATE ARRAYLIST HERE
cat.addItem(new Music(1111,"White and Nerdy",2.50,"\"Weird Al\" Yankovic"));
cat.addItem(new Music(2222,"Amish Paradise",2.22,"\"Weird Al\" Yankovic"));
cat.addItem(new Music(3333,"The Saga Begins",2.00,"\"Weird Al\" Yankovic"));
cat.addItem(new Movie(4444,"UHF",9.99,"\"Weird Al\" Yankovic"));
cat.addItem(new Movie(5555,"The Dark Crystal",8.99,"\"Jim Henson"));
cat.addItem(new Movie(6666,"Die Hard",13.99,"Bruce Willis"));
cat.addItem(new Book(7777,"When I Grow Up",7.98,"\"Weird Al\" Yankovic"));
cat.addItem(new Book(8888,"The Chronicles of Pern: First Fall",5.99,"\"Anne McCaffrey"));
cat.addItem(new Book(9999,"Get gud you scrub",2.50,"Steve \"Troll\" Rathier"));
编辑:这是我的目录类的构造函数
public Catalog()
{
//makes empty arraylist
// initialise instance variables
items = new ArrayList<>(MAX);
size = 0;
}
答案 0 :(得分:2)
有一个简单的方法:
public class MyClass {
List<Object> myObjects;
Object[] myArrayObjects;
void myMethod() {
if (myArrayObjects == null || myArrayObjects.length == 0) {
//Array is empty
} else {
//Array has some data
}
if (myObjects == null || myObjects.size() == 0) {
//List is empty
} else {
//List has some data
}
}
}
另一个我认为更好的解决方案是这样的
public class Catalog {
List<Object> items;
public Catalog() {
items = new ArrayList<>();
}
public void addItem(Object object) {
items.add(object);
}
public boolean isEmpty() {
return items.isEmpty();
}
public int size() {
return items.size();
}
}
该类的用法如下
public class MyClass {
Catalog catalog;
public MyClass() {
this.catalog = new Catalog();
}
void printCatalog() {
if (catalog.isEmpty()) {
//catalog is empty
} else {
//catalog has some data you can print them
}
}
void addItems(Object object) {
catalog.addItem(object);
}
}
答案 1 :(得分:0)
java.util.ArrayList也具有 size()方法。 您可以使用它来检查列表大小,如果为0,则列表为空。