0

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?

Makoto
  • 104,088
  • 27
  • 192
  • 230
jkface
  • 9
  • 2

5 Answers5

3

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();
     ......
  }
}
Robert Louis Murphy
  • 1,558
  • 1
  • 16
  • 29
3

You can instantiate your variable a while declaring.

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

   ...
 }
2

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

Makoto
  • 104,088
  • 27
  • 192
  • 230
1

Put it in the field declaration:

private Queue<Double> a = new LinkedList<Double>();
Jordão
  • 55,340
  • 13
  • 112
  • 144
1

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.

Torious
  • 3,364
  • 17
  • 24