title: Java Arraylist of objects Contains/equals
body: <p>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.</p>
  
  <p>Let's say I am working on a book collection and I have an author object:</p>
  
  <pre><code>class Author {
    String name;
    &lt;other data&gt;;
    int bookCount;
  
    public Author(String n) {
       name = n;
    }
  
    public boolean equals(Author other) {
       if (other.name.equals(name)) { return true;}
       return false;
    }
  }
  </code></pre>
  
  <p>So I create a list of authors instantiated as an arrayList:</p>
  
  <pre><code>Arraylist&lt;Author&gt; writers;
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>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++;
  }
  </code></pre>
  
  <p>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). </p>
  
  <p>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?</p>
  
  <p>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:</p>
  
  <pre><code>Arraylist&lt;Author&gt; {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++;
  }
  </code></pre>
  
  <p>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.</p>