Search code examples
javacastingcoding-style

How to properly cast generic collections in Java?


Let's say that I have initially declared and defined a set of integers as follows:

Set<Integer> s = new TreeSet<>();

Now, later I want to use methods that are specific to a TreeSet. And imagine that I need to this a lot of times in my project. Which of following ways is considered a better practice to stick to?

1- Writing this before starting to use s, at the beginning of my method

s = (TreeSet) s;

2- Writing with the type included (again at the beginning of my method)

s = (TreeSet<Integer>) s;

3- Casting from Set to TreeSet only at times that I need to access a TreeSet specific method

Integer x = ((TreeSet)s).first();

Solution

  • As others have said, you don't need to lose the context of the Set being a TreeSet after your declaration if it is important.

    A TreeSet is-a Set, so you should be able to pass it around as a Set.

    For example:

    Set<Integer> getSetButDoSomethingSpecial() {
      TreeSet<Integer> treeSet = new TreeSet<>();
      //Do something specific to treeSet
      return treeSet;
    }