How to use compareTo with a node? - java

I have this simple node:
public class Node<T> implements Comparable<Node>{
T value;
Node<T> next;
public Node(T value){
this.value = value;
this.next = null;
}
public int compareTo(Node other){
return this.value.compareTo(other.value);
}
}
Eclipse is asking me to cast "this.value". Casting it with int doesnt work. How should it be done?

Your declaration of T does not "extend" Comparable, so you can't use it to compare.
You could change it to:
public class Node<T extends Comparable<T>> implements Comparable<Node<T>>{
T value;
Node<T> next;
public Node(T value){
this.value = value;
this.next = null;
}
public int compareTo(Node<T> other){
return this.value.compareTo(other.value);
}
}
This assumes that T implements Comparable.
Otherwise, if T is not really a comparable, you may just do the comparison at the Node level. But you should probably still declare your class like this
public class Node<T extends Something>
so that you have methods from Something to work with when doing the comparison.
If I go back at the beginning: When you instantiate your Node, you do something like this:
Node<MyType> node = new Node<MyType>();
MyType becomes your T. Is MyType a comparable ? If so, you may declare your class as shown above. Otherwise, you will not be able to do T.compareTo (aka MyType.compareTo), so you need to perform your comparison using other fields from MyType.
I hope this is clear enough..

Related

Java - Class that extends a class, and has a component that extends the other class' component

To clarify, this is a Stack and MinStack.
They use StackNode and MinStackNode respectively.
I'm trying to get MinStack to extend Stack and MinStackNode to extend StackNode. However, when I do so MinStack uses StackNode instead of MinStackNode.
This is because Stack uses StackNode and MinStack inherits this. I want MinStack to use MinStackNode.
Organization:
StackNode -> Stack
inherited by the classes below
MinStackNode -> MinStack
Any help would be appreciated. Thanks!
Code snippet for Stack:
public class Stack<E> implements StackInterface<E> {
private StackNode<E> top;
private int size;
public Stack(E data){
StackNode<E> node = new StackNode<E>(data);
this.top = node;
}
public Stack(){
this.top = null;
}
}
MinStack:
public class MinStack<E extends Comparable<E>> extends Stack<E>{
private MinStackNode<E> top;
public MinStack(Stack<E> s){
super(s);
}
}
StackNode:
public class StackNode<E> {
private E data;
private StackNode<E> next;
public StackNode(E data){
this.data = data;
this.next = null;
}
}
MinStackNode:
public class MinStackNode<T> extends StackNode<T> {
private T min;
public MinStackNode(Comparator<T> comparator, T data) {
super(data);
this.min = minimum(this.getNext().getMin(), this.getData());
}
}
For space I didn't include some methods such as MinStackNode's minimum. If needed I'll include them.
Well if MinStackNode inherits StackNode then you don't necessarily have to include the variable top in MinStackNode since a valid declaration already exists in StackNode. However you will need to cast the value to MinStackNode when you need to use any of the non-inherited properties/methods.
I think your problem here is that what you expect to be of type MinStackNode is actually of this type, but is being stored in a variable of a more general type and so must be cast.

Problems converting Integer object to type int [duplicate]

This question already has answers here:
Java class with concrete type as parameter
(2 answers)
Closed 7 years ago.
Not sure what is going on here. Seems like an auto-boxing problem but I've been stuck on this for awhile and thought it might benefit me to stop stressing out and get some more experienced hands on this. The assignment is essentially implementing a BST and extending it to an implementation of an AVL and then running performance tests. To simplify things we can stick with using Integer as the generic.
The problem I am having is when comparing two Nodes. Autoboxing is not taking place and the intValue() method is not recognized.
public class BinaryNode<Integer> implements Comparable<Integer>
{
Integer data;
BinaryNode<Integer> leftChild;
BinaryNode<Integer> rightChild;
int height;
BinaryNode(Integer data)
{
this(data, null, null);
}
BinaryNode(Integer data, BinaryNode<Integer> lt, BinaryNode<Integer> rt)
{
this.data = data;
this.leftChild = lt;
this.rightChild = rt;
}
public Integer getData()
{
return this.data;
}
public BinaryNode<Integer> getLeft()
{
return leftChild;
}
public void setLeft(BinaryNode newNode)
{
this.leftChild = newNode;
}
public BinaryNode<Integer> getRight()
{
return rightChild;
}
public void setRight(BinaryNode newNode)
{
this.rightChild = newNode;
}
#Override
public int compareTo(BinaryNode<Integer> otherNode)
{
return this.getData() - otherNode.getData();
}
}
Edit: Thanks for the quick feedback. It was just the sort of interaction I needed to look at this differently and understand the quirky behavior I was encountering. Unfortunately I am bound to make this BinaryNode a generic class but the trick was to swap out all of the with or as the book's conventions prefer to use .
The best solution was to change the BinaryNode<Integer> to BinaryNode<AnyType> and remove the compareTo from this class. Now that I am no longer overshadowing java.lang.Integer I can reliably use the Integer.compareTo method as I originally intended.
For the curious, here is the TreePrinter class that I have to interact with that uses the parameterized BinaryNode class. http://www.cs.sjsu.edu/~mak/CS146/assignments/3/TreePrinter.java
In class BinaryNode<Integer>, Integer is a generic type parameter, not the Integer class.
change
public class BinaryNode<Integer> implements Comparable<Integer>
to
public class BinaryNode implements Comparable<Integer>
And change any appearance of BinaryNode<Integer> to BinaryNode.
If you wanted the BinaryNode class to takes a generic data type, you wouldn't write code specific to Integer data type (for example, return this.getData() - otherNode.getData() will never compile if getData() returns some generic type parameter T).
public class BinaryNode<Integer> implements Comparable<Integer>
Says that you have a new generic type named Integer. This is not the java.lang.Integer. This is why you're having issues, because they are completely different.
As Soritos Delimanolis pointed out, it would be better to just drop the generic type altogether.

Generic Iterator implementation in java

I have the following design:
I have an Abstract class Instance,
I have a class Library that extends Instance and
I have a class File that also extends Instance
I've created my own linked list implementation and it's defined as follows:
public class List<T extends Instance> implements Iterable {
//some other code here
public Iterator iterator(){
return new ListIterator(this);
}
now I've created a class
public class ListIterator<T extends Instance> implements Iterator<T> {
private List thisList;
private Node current;
public ListIterator(List l){
thisList=l;
current=thisList.head.next;
}
#Override
public boolean hasNext() {
if(current==null)
return false;
return false;
}
#Override
public T next() {
Node temp=current;
current=current.next;
return temp.data;
}
}
Where Node is
public class Node<T extends Instance> {
public Node<T> next;
public Node<T> prev;
public T data;
public Node(T data,Node prev, Node next){
this.data=data;
this.prev=prev;
this.next=next;
}
}
so my problem is as follows: the line return temp.data rises an error:
Type mismatch - cannot convert from Instance to T.
What is wrong with this code?
I'd say that Node.data is a reference to an Instance object? If that is the case, the compiler can't automatically change an Instance to a T, because even though T is an Instance object (T extends Instance), any given Instance might not be a T.
The Java Generics tutorial explains it: http://docs.oracle.com/javase/tutorial/extra/generics/subtype.html
Also, in your List<T> class, you should be specifying Iterator and ListIterator as generic using Iterator<T> and ListIterator<T>, or else the compiler won't be able to handle the generics properly. Your Node reference also needs to be generic: Node<T>
Hence you should be using
private Node<T> current;
and
public T next() {
Node<T> temp=current;
current=current.next;
return temp.data;
}
The compiler will usually warn you when you're using a raw type for a generic class.
Did no one notice the bug:
public boolean hasNext() {
if(current==null)
return false;
return false;
}
This is an invariant. Unless I am missing something, the iterator will very quickly return 0 elements!

using compareTo in Binary Search Tree program

I've been working on this program for a few days now and I've implemented a few of the primary methods in my BinarySearchTree class such as insert and delete. Insert seemed to be working fine, but once I try to delete I kept getting errors. So after playing around with the code I wanted to test my compareTo methods. I created two new nodes and tried to compare them and I get this error:
Exception in thread "main" java.lang.ClassCastException: TreeNode cannot be cast to java.lang.Integer
at java.lang.Integer.compareTo(Unknown Source)
at TreeNode.compareTo(TreeNode.java:16)
at BinarySearchTree.myComparision(BinarySearchTree.java:177)
at main.main(main.java:14)
Here is my class for creating the nodes:
public class TreeNode<T> implements Comparable
{
protected TreeNode<T> left, right;
protected Object element;
public TreeNode(Object obj)
{
element=obj;
left=null;
right=null;
}
public int compareTo(Object node)
{
return ((Comparable) this.element).compareTo(node);
}
}
Am I doing the compareTo method all wrong? I would like to create trees that can handle integers and strings (seperatly of course)
To be sure that the element indeed is a comparable object, and avoid all the casts, you could do something like this:
public class TreeNode<T extends Comparable<? super T>>
implements Comparable<TreeNode<T>> {
protected TreeNode<T> left, right;
protected T element;
public TreeNode(T obj) {
element = obj;
left = null;
right = null;
}
#Override
public int compareTo(TreeNode<T> node) {
return element.compareTo(node.element);
}
}
For an usage example:
TreeNode<Integer> node1 = new TreeNode<Integer>(2);
TreeNode<Integer> node2 = new TreeNode<Integer>(3);
System.out.println(node1.compareTo(node2));
The above snippet prints -1 on the console.
compareTo method is applied against TreeNode (passed as node parameter), while you compare it with this.element, which is an Object contained in the TreeNode. Simply change to:
return ((Comparable) this.element).compareTo(node.getElement());
assuming you have getElement method.
Try
public <T> int compareTo(Object node)
{
return ((Comparable) this.element).compareTo( ( TreeNode<T> ) node ).element);
}

Write a tree class in Java where each level has a unique object type

I need to write a tree class in Java where each level has a unique object type. The way it is written below does not take advantage of generics and causes alot of duplicate code. Is there a way to write this with Generics ?
public class NodeB {
private String nodeValue;
//private List<NodeB> childNodes;
// constructors
// getters/setters
}
public class NodeA {
private String value;
private List<NodeB> childNodes;
// constructors
// getters/setters
}
public class Tree {
private String value;
private List<NodeA> childNodes;
// constructors
// tree methods
}
This is simplistic implementation, but enough to give general idea:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class GenericNode {
public static abstract class AbstractNode<V, N> {
private V value;
private List<N> children;
public AbstractNode(V value, N... children) {
this.value = value;
this.children = children != null ? Arrays.asList(children)
: Collections.<N> emptyList();
}
public V getValue() {
return value;
}
public List<N> getChildren() {
return children;
}
public int getNumberOfChildren() {
return children.size();
}
#Override
public String toString() {
return value.toString() + "->" + children.toString();
}
}
// leaf node type, ignore type of children
public static class NodeB extends AbstractNode<String, Object> {
public NodeB(String value, Object... nodes) {
super(value, nodes);
}
}
// example of typical node in the mid of tree
public static class NodeA extends AbstractNode<String, NodeB> {
public NodeA(String value, NodeB... nodes) {
super(value, nodes);
}
}
// top level node type
public static class Tree extends AbstractNode<String, NodeA> {
public Tree(String value, NodeA... nodes) {
super(value, nodes);
}
}
#SuppressWarnings({ "rawtypes", "unchecked" })
public static <V, N extends AbstractNode> int getNodeCount(
AbstractNode<V, N> node) {
int nodeCount = node.getChildren().size();
for (N child : node.getChildren()) {
nodeCount += getNodeCount(child);
}
return nodeCount;
}
public static void main(String[] args) {
NodeB nodeB1 = new NodeB("Leaf node 1");
NodeB nodeB2 = new NodeB("Leaf node 2");
NodeA nodeA = new NodeA("Node with children", nodeB1, nodeB2);
NodeA emptyNodeA = new NodeA("Empty node");
Tree tree = new Tree("Tree", nodeA, emptyNodeA);
System.out.println(tree);
System.out.println(1 + getNodeCount(tree));
}
}
You could make N and V types implement specific interfaces so it will be possible to call some common operations on values and/or children.
EDIT: updated implementation with recursive method for node count retrieval
All you need is a Pair<A, B>. Example of trees:
Pair<A, Pair<B, C>>
Pair<Pair<A, B>, Pair<C, D>>
Pair<Pair<Pair<A, B>, Pair<C, D>>, Pair<Pair<E, F>, Pair<G, H>>
ps: don't do this. :)
This is an ideal spot for everything inheriting from "Node", but even that is unnecessary.\
What you probably want is a single generic "Node" object that contains references to your different classes (use composition before inheritance).
At that point, each of your different classes probably has something that can be done to them (otherwise why are they all in the same data structure?) Have them implement a common interface with this common functionality. The node class can delegate to this interface, or some other class can extract the class by this interface and act on it.
This would be better than trying to force something to also BE a node--do one simple thing and do it well.
--edit--
I can't really add an example that is relevant to you because you didn't post anything about your scenario.
But let's say that you have these different classes A, B * C. First of all are they related AT ALL aside from all being children of Object? Let's say they all implement interface "Iface". (If not, you can just replace Iface with "Object", but this really implies a bad design.)
Anyway, your "Node" object is just one object--
public class Node {
private List<node> children;
private Iface myObject;
... setters, getters, tree implementation, tree navigation, related garbage...
}
Now this is enough to create your tree. One thing that you might be able to do to make things smoother, have "Node implements Iface" and delegate any calls to it's object. For instance, if Iface contains an eat(Food foodtype) method, your node could implement Iface and have a method:
public void eat(Food foodtype) {
myObject.eat(foodtype);
}
This would make the "Node" class act as though it was the class it contained.
By the way--another relatively good idea at this point would be to make myObject "private final" and ensure it is not null in the constructor. That way you would always know it was set and none of your delegated members would have to do null checks.
I don't think generics are going to help you much in this case. Instead of having a different class for each level in the tree. What about one node class that has children and store a different class on each level. That should help eliminate a lot of the duplication.
I'm fairly new to Java, so this might have issues I'm not aware of, but it seems to work on a simple level at least.
Define your main Node class - this one will be the root of the tree.
public class NodeA {
private String _value;
private ArrayList<NodeA> _children;
private int _depth;
public NodeA (String value, int depth) {
_value = value;
_children = new ArrayList<NodeA>();
_depth = depth;
}
//probably want getters for _children and _value here
//this makes a new child, with its type depending on the depth of the tree it will
//be placed at. NodeB and NodeC will both inherit from NodeA
public void add(String value) {
switch (_depth) {
case 0:
_children.add(new NodeB(value, _depth+1));
break;
case 1:
_children.add(new NodeC(value, _depth+1));
break;
}
}
The add() method is going to create a new child for the node using the specified value. If you initialize the root of the tree as a NodeA with depth 0, you can add children to nodes and the tree should end up populated so that the next level contains all NodeB's, and the next all NodeC's. The code for NodeB and NodeC is super simple and could be replicated to create an arbitrary amount of Node levels (here is that code).
public class NodeB extends NodeA {
public NodeB(String value, int depth) {
super(value, depth);
}
//nothing else needed!
The code for NodeC is identical, except for the obvious replacements of B's with C's.
Hope this helps / is the kind of answer you wanted!

Categories