Results 1 to 4 of 4
Thread: Generics Question
- 02-11-2011, 03:51 AM #1
Member
- Join Date
- Dec 2010
- Posts
- 12
- Rep Power
- 0
Generics Question
Okay so I've been writing a Binary Search Tree for school and have run into a problem.
My BST class is generic and in one of my methods I need to compare data in nodes to find their place in the tree.
The problem is that when I compile my main class it says "cannot find symbol method compareTo(java.lang.Object)". How can I tell my BinarySearchTree class to only accept generic types that implement Comparable?
These are my classes.
Java Code:public class BinarySearchTree<T> { BTNode root; public void insert(T obj){ BTNode node = new BTNode<T>(obj); if(root == null){ root = node; System.out.println("hmm"); } else{ if(obj.compareTo(root.getData()) > 0){ System.out.println("Yay"); } else{ System.out.println("yay2"); } } } }Java Code:public class BTNode<T> { T data; BTNode left; BTNode right; public BTNode(T obj){ data = obj; } public void setData(T obj){ data = obj; } public T getData(){ return data; } public void setLeft(BTNode node){ left = node; } public BTNode getLeft(){ return left; } public void setRight(BTNode node){ right = node; } public BTNode getRight(){ return right; } }Java Code:public class Index implements Comparable<Index>{ int pos; String ssn; public Index(String ssNum, int i) { ssn = ssNum; pos = i; } public int compareTo(Index index){ return ssn.compareTo(index.getSSN()); } public int getIndex(){ return pos; } public String getSSN(){ return ssn; } }Java Code:public class DatabaseMain { public static void main(String [] args){ BinarySearchTree<Index> bst = new BinarySearchTree<Index>(); bst.insert(new Index("003436857", 0)); bst.insert(new Index("112576757", 1)); } }
-
Get your T to extend Comparable<T>
Your other classes that are generic should do the same, and you will need to "genericize" the declaration of your fields of these classes that need it. i.e.,Java Code:class BinarySearchTree<T extends Comparable<T>> {
Java Code:class BinarySearchTree<T extends Comparable<T>> { BTNode<T> root; // don't forget generics here as well.
- 02-11-2011, 04:20 AM #3
Member
- Join Date
- Dec 2010
- Posts
- 12
- Rep Power
- 0
It worked! Thanks Fubarable!
-
Similar Threads
-
Question regarding generics
By Leaflord in forum Advanced JavaReplies: 9Last Post: 08-29-2009, 02:24 PM -
Generics & Inheritance Question
By Lee Rhodes in forum Advanced JavaReplies: 3Last Post: 07-03-2009, 05:04 AM -
Generics Question
By jdgallag in forum New To JavaReplies: 8Last Post: 10-28-2008, 06:15 PM -
generics
By tascoa in forum Forum LobbyReplies: 2Last Post: 10-09-2008, 07:58 PM -
Question about java generics
By Arrowx7 in forum New To JavaReplies: 1Last Post: 08-14-2008, 02:37 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks