I want to make a generic BST, that can be made up of any data type, but i'm not sure how I could add things to the tree, if my BST is generic. All of my needed code is below. I want my BST made up of Locations, and sorted by the x variable. Any help is appreciated.
Major thanks for looking.
public void add(E element)
{
if (root == null)
root = element;
if (element < root)
add(element, root.leftChild);
if (element > root)
add(element, root.rightChild);
else
System.out.println("Element Already Exists");
}
private void add(E element, E currLoc)
{
if (currLoc == null)
currLoc = element;
if (element < root)
add(element, currLoc.leftChild);
if (element > root)
add(element, currLoc.rightChild);
else
System.out.println("Element Already Exists);
}
Other Code
public class BinaryNode<E>
{
E BinaryNode;
BinaryNode nextBinaryNode;
BinaryNode prevBinaryNode;
public BinaryNode()
{
BinaryNode = null;
nextBinaryNode = null;
prevBinaryNode = null;
}
}
public class Location<AnyType> extends BinaryNode
{
String name;
int x,y;
public Location()
{
name = null;
x = 0;
y = 0;
}
public Location(String newName, int xCord, int yCord)
{
name = newName;
x = xCord;
y = yCord;
}
public int equals(Location othe开发者_运维问答rScene)
{
return name.compareToIgnoreCase(otherScene.name);
}
}
You can constrain your type to implement Comparable<? super E>
:
public class BinarySearchTree<E extends Comparable<? super E>>
Then you can call compareTo
:
// Instead of if (element < root)
if (element.compareTo(root) < 0)
(etc)
Alternatively, you could force the caller to pass in a Comparator<E>
when the search tree is constructed, and then use that to compare elements. That's actually a more flexible solution in my view - it means you could create different binary search trees for the same element type, but ordering them in different ways.
精彩评论