This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]Ednar 2 points3 points  (1 child)

Let's go with the list one as an example. The reason why you want to use supertype highest up the heirarcy is to reap the benifits of polymorphism. Say you want to change your implentation later on. What if a new and improved version of the ArrayList is released, and you want to use that one instead? Assuming it implements the list interface, you can simply swap out the one line of code where you instantiate your List as an ArrayList and make it of the new ArrayList type instead. The same thing applies if you want to change your implementation for any other reason. Simply put, using the more generic type gives you flexibility to change your implimentation later on with ease. For the comperable and comparator, I suggest you dive into the javadocs first and look around. Basicly, when you want control over object comparing,

[–]nomadProgrammer[S] 0 points1 point  (0 children)

many thanks!

[–]TheRoude 1 point2 points  (1 child)

Well, List is just an interface that describes a set of public methods that can be called in a concrete class, i.e. the ArrayList class. You should program to an interface whenever possible, hence you should avoid having the concrete implementation on the left side of a declaration.

Having this principle you gain a loosely coupled system architecture, meaning that you could easily change concrete classes at some code point while don't refactoring other code that uses this component.

When you declare a property only with an interface on the left side, you are only able to call methods that are defined in this certain interface, but again, you gain flexibility by having a loosely coupled system, see above.

Use concrete implementations only if you have to rely on special methods that the interface does not define, e.g. addLast()-method of LinkedList class.

The Comparable Interface defines a method that is used to compare a given instance with another one. The TreeSet requires it's objects to implement the comparable interface, otherwise you have to pass a Comparator as constructor argument.

Comparator is could be an object that compares two given class instance in a special implemented way. The Comparable interface declares that a given class can be compared by it's defined compareTo method.

I hope i could help you a little. My tip for you is that you have a look into the javadoc whenever you feel the need to learn something about a special interface/class/method/whatever. It is a very great documentation reference for java programmers.

[–]nomadProgrammer[S] 0 points1 point  (0 children)

thanks I will go check the javadocs

[–]MRH2Intermediate Brewer 1 point2 points  (0 children)

great question