Alicia
Alicia

Reputation: 174

Anything wrong with defining a java class with an array of elements of that class as one of its fields?

My application model consists of disorders, each of which has innate attributes (id, name, incidence, etc.) and relationships to other disorders (e.g. risk factors, precipitating disorders, findings). I've considered the following two object models:

The first: nested classes:

class DiagnosticElement{
      Disorder disorder;
      List<Disorder> relatedDisorders;

      static class Disorder {
          int id;
          String name;
          double incidence;
          Disorder(id){
              this.id=id;
          }

    }
}

The second:

class Disorder {
        int id;
        String name;
        double incidence;
        List<Disorder> relatedDisorders;

        Disorder(id){
            this.id=id;
            this.relatedDisorders=new ArrayList<Disorder>()
        }

    }

The second approach seems simpler. Of course I must first instantiate Disorder objects before I can reference them in the ArrayList. Is one approach better than the other?

Upvotes: 3

Views: 81

Answers (2)

Jan D&#246;rrenhaus
Jan D&#246;rrenhaus

Reputation: 6717

Careful, your line

List<Disorder> relatedDisorders=new ArrayList<Disorder>()

in the constructor will create a local variable relatedDisorders, which you initialize. You did not initialize the class field.

Anyway, there is nothing wrong with having references to your own class inside your class. That is how every linked list works.

Upvotes: 0

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

There's nothing wrong with approach number two, and in fact it is used quite often. Think of Trees or LinkedLists for instance where nodes hold links to other nodes. You do have to be careful if you create objects of the same type inside of a constructor though as this can lead to code that runs forever.

Upvotes: 7

Related Questions