我看过很多地方,大多数 arraylist 示例都使用“String”作为元素,但是很难找到使用对象的地方。
假设我正在处理书籍收藏,并且我有一个作者对象:
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。我可以在 Author 中的名称上写一个 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 并覆盖包含和 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 签名,并且将其内联几乎与创建新类的工作量相同。