我查看了很多地方,大多数 arraylist 示例都使用“String”作为元素,但是很难找到使用对象的地方。
假设我正在制作一个图书 Collection ,并且我有一个作者对象:
class Author {
String name;
<other data>;
int bookCount;
public Author(String n) {
name = n;
}
public boolean equals(Author other) {
if (other.name.equals(name)) { return true;}
return false;
}
}
因此,我创建了一个实例化为 arrayList 的作者列表:
Arraylist<Author> writers;
所以我想查明作者是否存在,如果不存在则创建一个新条目,如果存在则增加 bookCount。我可以在作者的名字上写一个 equals 方法(如上所示),然后执行如下操作:
bookAuthor = "James Gosling"; // normally an input
Author current = new Author(bookAuthor);
if (!writers.contains(current)) {
writers.add(current);
} else {
writers.get(writers.indexOf(current)).bookCount++;
}
我相信这会起作用,我发现创建大量对象只是为了在比较后丢弃它们是令人反感的,但我遇到的问题是 Author 的正常构造函数并不那么简单,并且涉及数据库查找(非常昂贵)。
这意味着在这种情况下仍然可以使用仅名称构造函数,但我需要构造 Author 两次。我能想到的唯一其他方法是创建一个继承自 ArrayList 并覆盖 Contains 和 indexOf 的新类。这看起来开销很大,然后我是否需要在新类中重写 equals 或 hashCode 或其他内容?
我是否遗漏了一些东西,是否没有某种方法可以提供内联函数或使使用对象容器更容易的方法? 我希望有人可以做这样的事情:
Arraylist<Author> {equals(String x) { if (x = this.name) { return true;} return false; } writers;
if (!writers.contains(bookAuthor)) {
writers.add(new Author(bookAuthor,dbconn);
} else {
writers.get(writers.indexOf(bookAuthor)).bookCount++;
}
但是,contains 和 indexOf 当然没有 String 签名,将其内联起来几乎与创建新类的工作量相同。
最佳答案
也许你可以使用Map<String,Author>
对于名称->作者映射,这将解决它
关于Java 对象的数组列表包含/等于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15848195/