2
class Pair<A,B> {
    final A first;
    final B sec;

    Pair(A f, B s){
        this.first = f;
        this.sec = s;
    }
}

Is there a way to ensure that A and B are immutable types ?

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361

2 Answers2

4

No. There is no way to identify, let alone bound, a type as being immutable.

You could create a marker interface (one without methods, like Serializable) that is used in your project to identify immutable classes, and have your team adhere to it.

For example:

interface Immutable {}

class Pair<A extends Immutable, B extends Immutable> {
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722
2

No. In fact, there is no concept or "mutable" or "immutable" types in the language at all. "Immutable" is simply a term we use to describe a type that happens to not offer any methods or public fields that allow you to change any internal state. Other than that, there is no difference between how "mutable" and "immutable" types work.

newacct
  • 119,665
  • 29
  • 163
  • 224