小编moc*_*ird的帖子

为什么 indexOf() 和 contains() 不能像我在 Java 中预期的那样工作?

// Objects for the bookstore I created

BookStore bookStore = new BookStore("Subu's Book Store","Perambur");
bookStore.addItem(new Item("Animal Farm",20));
bookStore.addItem(new Item("Animal Farm",20));
Run Code Online (Sandbox Code Playgroud)

如果我使用原始工作方法,则输出:

Animal Farm has been bought
Animal Farm is already bought
Run Code Online (Sandbox Code Playgroud)

使用 contains() 不起作用的方法的输出

Animal Farm has been bought
Animal Farm has been bought
Run Code Online (Sandbox Code Playgroud)

使用 indexof() 不起作用的方法的输出

-1
Animal Farm has been bought
-1
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index -1 out of bounds for length 1
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:372)
at java.base/java.util.ArrayList.get(ArrayList.java:459)
at com.company.subusproject.BookStore.searchItem(BookStore.java:41)
at …
Run Code Online (Sandbox Code Playgroud)

java arrays contains object indexof

0
推荐指数
1
解决办法
143
查看次数

标签 统计

arrays ×1

contains ×1

indexof ×1

java ×1

object ×1