D Lee D Lee - 7 months ago 8
Java Question

Java - Can object method call be done simultaneously with object instantiation?

I'm trying to use java class

BitSet
as a field for a customized class. And I want the class to use a default BitSet with all bits set.

import java.util.BitSet;

public class MyClass {
private BitSet mask;

public MyClass() {
this(new BitSet(4));
// want to set all bits first
// something like
// this( new BitSet(4).set(0,3) );
}

public MyClass(BitSet mask) {
this.mask = mask;
}
}


By default
BitSet
constructor unsets all bits. So before I send it as an anonymous object, I would like call
set(int, int)
method to set all bits. I know that I could simply initialize the field
mask
to a new
BitSet
and then call
set(int, int)
method from there.

However, in general I'm wondering is it possible to access an instance method at time of object instantiation?

Answer

Why not writing a separate constructor that allows for the BitSet initialization? Using Java 8, this could look like something like this:

public class MyClass {
  private BitSet mask;
  public MyClass() {
    this(new BitSet(4),(m)->m.set(0,3));
  }
  public MyClass(BitSet mask,Consumer<BitSet> initializer) {
    initializer.accept(mask);
    this.mask = mask;
  }
}

You can even make that more generic by introducing a static method with type parameters:

public static <T> T initialize(T t,Consumer<T> initializer) {
  initializer.accept(t);
  return t;
} 

In that case, the earlier MyClass would look as follows:

public class MyClass {
  private BitSet mask;
  public MyClass() {
    this(initialize(new BitSet(4),(m)->m.set(0,3)));
  }
  public MyClass(BitSet mask) {
    this.mask = mask;
  }
}

UPDATE

And there is one more way, without introducing new methods or constructors:

public class MyClass {
  private BitSet mask;
  public MyClass() {
    this(new BitSet(4) {{ set(0,3); }});
  }
  public MyClass(BitSet mask) {
    this.mask = mask;
  }
}

An anonymous class is being instantiated by extending BitSet and adding an instance initialization block, hence the double curly braces.

Comments