jkface
jkface

Reputation: 9

Eliminating redundancy in multiple constructors

If anyone could tell me whether my code is redundant (and if it is, possible solutions to eliminate redundancy) I would very appreciate it.

public class Question {
  private Queue<Double> a;

  public Question(double XXX) {
     a = new LinkedList<Double>();  // REDUNDANT?
     ......
  }

  public Question(double[] YYY) {
     a = new LinkedList<Double>();  // REDUNDANT?
     ......
  }
}

Basically, one constructor takes in a double value while the other constructor takes in an array of double numbers. Is there any way to instantiate the Queue only once?

Upvotes: 0

Views: 610

Answers (5)

Torious
Torious

Reputation: 3424

You may also want to consider this:

public class Question {
    private Queue<Double> a;

    public Question(double ... ds) {
        a = new LinkedList<>(Arrays.asList(ArrayUtils.toObject(ds)));
    }
}

This uses the varargs constructor, to which you can pass a single double, multiple doubles, or an array of doubles. So you can do:

new Question(1, 2, 3);
new Question(1);
new Question(new double[] { 1, 2, 3 } );

Note: ArrayUtils is part of the Apache Commons Lang.

Upvotes: 1

Robert Louis Murphy
Robert Louis Murphy

Reputation: 1628

When using Java 7 and NetBeans or other IDEs, the IDE may flag

a = new LinkedList<Double>();

as redundant, you can use

a = new LinkedList<>();

instead. But if you are just asking about actual redundancy in your code, use:

public class Question {
  private Queue<Double> a;

  public Question() {
     a = new LinkedList<>();
  }

  public Question(double XXX) {
     this();
     ......
  }

  public Question(double[] YYY) {
     this();
     ......
  }
}

Upvotes: 3

user973999
user973999

Reputation:

You can instantiate your variable a while declaring.

public class Question {
   private Queue<Double> a = new LinkedList<Double>();

   ...
 }

Upvotes: 3

Makoto
Makoto

Reputation: 106518

You can use the this operator to call another constructor with the appropriate arguments.

Upvotes: 2

Jord&#227;o
Jord&#227;o

Reputation: 56537

Put it in the field declaration:

private Queue<Double> a = new LinkedList<Double>();

Upvotes: 1

Related Questions