Search code examples
javaobjectarraylistcontainers

Java Arraylist of objects Contains/equals


I have looked at a number of places and most arraylist examples use "String" as their element, however places that use objects are difficult to find.

Let's say I am working on a book collection and I have an author object:

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;
  }
}

So I create a list of authors instantiated as an arrayList:

Arraylist<Author> writers;

So I want to find out if an author exists and create a new entry if they don't or increment the bookCount if they do. I can write an equals method on the name in the Author (as shown above) and then do something like:

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++;
}

I believe that this will work, I find it objectionable to be creating a large number of objects just to throw them away after the comparison, but the problem I have is that the normal constructor for Author is not that simple, and involves a database lookup (so expensive).

This means the name only constructor can still be used in this case, but I then need to construct the Author twice. The only other way I can think of is to create a new class which inherits from ArrayList and overrides Contains and indexOf. Which seems like a lot of overhead and then do I need to override equals or hashCode or something else in the new class too?

Am I missing something, is there not some way of providing an inline function or something to make using containers of objects more easy? I was hoping that one could do something like:

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++;
}

but of course the contains and indexOf don't have String signatures, and putting that inline is almost the same amount of work as creating the new class.


Solution

  • Mybe you can use Map<String,Author> for name-> Author mapping,this will get it around