Hello, I just started getting into Java a couple of weeks ago and i stumbled on a rather strange problem. Its about creating a Homogeneous or Heterogeneous collections in Java. So far I have created a generic BinaryTree class which can use every type i throw at it. So far just the basic one.
But i was wondering how would one implement a Collection which can take ANY type inside (such as String,Double,Integer) all at the same time inside the same collection. As far as i know the collection should be of type Object. The problem i am facing is how would i implement that witohut having to repeat my BinaryTree class and just replacing the generic with object. Is it possible to make it all in one Collection that can take The same and different types of objects at the same time.
For the objects , being diffrent types and all i guess i should override compareTo and i plan on comparing different objects based on their hash code. Comparing is irrelevant in this case since the main idea is to force the collection to take same and different types at the same time.
I want to take ArrayList as an example, it can do exactly that.
Stephan van Hulst wrote:Welcome to CodeRanch, Svetlozar!
I don't understand the problem. If you already have a generic BinaryTree, then why not just declare BinaryTree<Object>?
Well When i declare Tree<T extends Object & Comparable<T>> , compiler is not happy. Then if i try to do Tree<T extends Comparable<T>> i can't create Tree<Object> , compiler isn't happy again. so i went with Tree<T extends Object> implements Comparable<Object> , this way its all fine but i cant seem to understand how would i be able to compare say Integer to Integer , but i can compare Objects with hashCodes
Svetlozar Iliev wrote: ... this way its all fine but i cant seem to understand how would i be able to compare say Integer to Integer , but i can compare Objects with hashCodes
Comparable is not only used to determine equality, but is also used to determine which value is greater, etc. How do you do a "compare Objects with hashCodes"? There is no guaranteed way to determine which is greater (or even equality) with hashcodes -- as the relationship is not guaranteed to exist.
Also, on the same note, the Comparable<Object> type doesn't make much sense, as the Object class doesn't implement the Comparable interface.
Welcome to the ranch! Generics are one place where Java really could use some work and there are plenty of languages that do it better. Unfortunately it isn't going to change due to early decision in the language design. You might try Scala instead (compiles to the Jvm also) if you are looking for more flexibility in this area.