how to do this java recursive - java

I have this code:
static int countStu = 0;
public static int countStudent(Node<Student> lst) {
// pre : true
// post : res = number of students in list
if (lst != null) {
countStu++;
countStudent(lst.getNext());
}
return countStu;
}
The problem with this method is I must declare countStu outside the countStudent() method, which is not good in the case when I want to call countStudent() twice, it will make the returned value doubles. How do I solve this problem and able to call countStudent() unlimited times with correct results?

instead, return((lst == null)? 0 : (1 + countStudent(lst.getNext()))).

Change:
if(lst!=null){
countStu++;
countStudent(lst.getNext());
}
return countStu;
to
return lst==null ? 0 : (1+countStudent(lst.getNext()));

Assuming that this is your homework and you really must declare countStu outside (you shouldn't in any normal code), you can simply wrap the value in some class. Add set+get accessors and pass the object as a second argument to the function. Use it then, instead of the global / static variable.
Or simply don't use the variable at all and return the result + 1. Not sure if this is allowed by your rules.

In general when you are trying to do something like is useful to try to remove the explicit state handling somehow.
For example if you have to compute a function f(x) = G(f(x-1)) you can express G as a stateless method and follow the following pattern:
public static ResultType G(ResultType input) {
// compute G stateless
}
public static ResultType F(int x) {
return G(F(x - 1));
}
That way you don't have any side effects like you have with your current code. The downside is usually minor compared with what you are doing right now (the same stack depth is used overall).
The important thing is to make sure the G and F implementations are stateless (not using variables declared outside the method body scope).

Holding the state of the recursion in the static field would not be thread-safe. Instead hold the value in the stack.
I give you both a recursive example which would risk a StackOverflowError with as little as 6k nodes with a default heap as well as a loop version which doesn't suffer from this.
public class SO3765757 {
public static int countNodeRecursive(Node<?> node) {
if(node == null) {
debug("node is null");
return 0;
}
int count = 1 + countNodeRecursive(node.getNext());
debug(count + " = " + node.toString());
return count;
}
public static int countNodeLoop(Node<?> node) {
int count = 0;
for(Node<?> currentNode = node; currentNode != null; currentNode = currentNode.getNext()) {
count += 1;
debug(count + " = " + currentNode.toString());
}
return count;
}
public static void main(String[] args) {
int count = 10;
if(args.length > 0) {
try {
count = Integer.parseInt(args[0]);
} catch(NumberFormatException e) {
}
}
Node<Student> node = getNodeTest(count);
System.out.println("Loop count = " + countNodeLoop(node));
try {
System.out.println("Recursive count = " + countNodeRecursive(node));
} catch(StackOverflowError e) {
System.out.println("Recursive count caused " + e.getClass().getName());
}
}
private static void debug(String msg) {
System.out.println("DEBUG:" + msg);
}
private static <T> Node<T> getNodeTest(int count) {
Node<T> prevNode = null;
for(int i=0;i<count;i++) {
Node<T> node;
if(prevNode == null) {
node = new NodeImpl<T>();
} else {
node = new NodeImpl<T>(prevNode);
}
prevNode = node;
}
return prevNode;
}
private static interface Node<T> {
Node<T> getNext();
}
private static class NodeImpl<T> implements Node<T> {
private final Node<T> next;
public NodeImpl() {
this.next = null;
}
public NodeImpl(Node<T> next) {
this.next = next;
}
public Node<T> getNext() {
return next;
}
}
private static interface Student {
}
}

countStudent(lst.getNext());
why do i need to call again this , if lst.getNext() has null. precompute before calling recursion, there are different types.when u call this method countStudent from main method , check the lst value for not null , before recursion starts.
public static int
countStudent(Node lst) {
countStu++;
Node<Student> _tmp;
_tmp = lst.getNext();
if (_tmp != null )
countStudent(lst.getNext());
return countStu; }

Related

Adding height of binary tree to insert method

I am creating a program that inserts a character (number/letter) into a binary tree. So far, I'm able to produce an output but it's not what I expected. These are the problems I'm encountering:
The insert method is not able to print the correct height of the tree. I am not sure where I should insert my height++; statement to get the correct output.
The insert method is only able to add nodes to the right.
Expected Output: ht=3 [K=3 L=[K=1 R=[K=2]] R=[K=5 L=[K=4]]]
My Output: ht=4 [K=3 R=[K=1 R=[K=2 R=[K=5 R=[K=4]]]]
(all nodes are only added to the right 'R')
Here are my classes for reference:
Main Class
BST<Character> bst = new BST<>();
bst.insert('3');
bst.insert('1');
bst.insert('2');
bst.insert('5');
bst.insert('4');
System.out.println("ht=" + bst.height + " " + bst.toString());
BST Class - where the insert method is declared
public class BST<T> extends BT<T> {
// insert() method
public void insert(char k)
{
if (root == null) {
root = new BTNode(k);
return;
}
BTNode<T> n = root;
BTNode<T> p = null; // parent
while (n != null) {
p = n;
if (k < n.value) {
n = n.left;
} else {
n = n.right;
}
}
if (k < p.value) {
p.left = new BTNode(k);
} else {
p.right = new BTNode(k);
height++; // adds 1 to height when a new level is made
}
}
}
BTNode Class
public class BTNode<T> {
T info;
int value, level;
BTNode<T> left, right;
public BTNode(T el) {
this(el, null, null);
}
public BTNode(T el, BTNode<T> l, BTNode<T> r) {
info = el;
left = l;
right = r;
}
}
BT Class - where the toString method is declared
public class BT<T> {
BTNode<T> root = null;
int height = 0;
public BT() {
BTNode<T> node = new BTNode("");
}
// other methods
// toString()
public String toString() {
return toString(root);
}
public String toString(BTNode<T> n) {
String s = "";
if (n == null) {
return "";
}
if (n != null) {
s = "[K=" + n.info;
if (n.left != null) {
s = s + " L=" + toString(n.left) + "]";
}
if (n.right != null) {
s = s + " R=" + toString(n.right) + "]";
}
}
return s;
}
}
Hope you can help me out, thanks!
You have quite a few issues in your code. I'll list a few immediate items but you really will need to learn to use an interactive debugger and unit testing to resolve the sorts of issues you are seeing.
You refer to the value field in BTNode in your comparison but it is never set. You should really be referring to info (which is the actual data in the node).
But given info is a generic type you can't use standard comparison operators. Instead you'll need to define it as <T extends Comparable<T>> and then use n.info.compareTo(k) > 0.
The key passed into insert should also be of type T
Which means the other classes also need to ensure T extends Comparable.
Height is only incremented when nodes are added to the right which makes no sense.
Height needs to be increased only when a node is inserted further from the root than the current maximum. Something like the following:
int depth = 0;
while (n != null) {
depth++;
p = n;
...
}
depth++;
if (depth > height)
height = depth;
You should get used to making your fields private and accessing them through getters. In your case a compareValue method would likely make sense.

How to tidying my Java code because it has too many looping [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 10 months ago.
Improve this question
I have a Node class used to represent a tree structure. Within this class, I've defined a print method that should yield the following output:
data
--a (1024)
--b (256)
----ba (100)
------baa (500)
------bac (25)
----bc (150)
----bd (125)
----be (75)
--c (35)
----cb (30)
----ce (50)
This is how I've written my print method:
public void print(String name) {
Node node = this.find(name);
System.out.println(node.name);
if (node.childrensCount != 0) {
for (int i = 0; i < node.childrensCount; i++) {
Node children = node.childrens[i];
System.out.println("--" + children.name + " (" + children.value + ")");
if (children.childrensCount != 0) {
for (int j = 0; j < children.childrensCount; j++) {
Node grandChildren = children.childrens[j];
System.out.println("----" + grandChildren.name + " (" + grandChildren.value + ")");
if (grandChildren.childrensCount != 0) {
for (int k = 0; k < grandChildren.childrensCount; k++) {
Node greatGrandChildren = grandChildren.childrens[k];
System.out.println("------" + greatGrandChildren.name + " (" + greatGrandChildren.value + ")");
}
}
}
}
}
}
}
This is also the Node class implementation to better help you in understanding the scenario:
public class Node {
int value;
String name;
Node parent;
int childrensCount;
Node[] childrens = new Node[100];
public Node(int value, String name) {
this.value = value;
this.name = name;
this.childrensCount = 0;
}
public Node(String name) {
this.name = name;
}
public void addChildren(Node node)
{
this.childrens[childrensCount] = node;
childrensCount++;
}
public void setParent(Node parent)
{
this.parent = parent;
}
public boolean hasParent(){
return this.parent != null;
}
public int sumValue(){
int sum = 0;
sum += this.value;
for (int i = 0; i < childrensCount; i++) {
sum += childrens[i].value;
}
return sum;
}
}
I think my code is quite dirty and can be improved. I'd like to define a recursive method but I still don't understand how recursion works. Could someone help me with that?
You can do it using recursion. Rather than try to reconstruct your data in all its complexity I created a simple example using my own node class.
class MyNode {
String name;
List<MyNode> nodeList;
public MyNode(String name) {
this.name = name;
}
public MyNode setNodeList(List<MyNode> list) {
nodeList = list;
return this;
}
#Override
public String toString() {
return name;
}
public List<MyNode> getNodeList() {
return nodeList;
}
}
MyNode m = new MyNode("a");
List<MyNode> list1 =
List.of(new MyNode("aaa"), new MyNode("aab"),
new MyNode("aac"), new MyNode("aad"));
List<MyNode> list2 = List.of(new MyNode("aba"),
new MyNode("abb"), new MyNode("abc"));
List<MyNode> list3 = List.of(new MyNode("aca"),
new MyNode("acb"), new MyNode("acc"));
List<MyNode> list4 = List.of(new MyNode("ada"),
new MyNode("adb"), new MyNode("adc"));
List<MyNode> mainlist = List.of(new MyNode("aa").setNodeList(list1),
new MyNode("ab").setNodeList(list2), new MyNode("ac").setNodeList(list3), new MyNode("ad").setNodeList(list4));
m.setNodeList(mainlist);
print(m,1);
prints
--a
----aa
------aaa
------aab
------aac
------aad
----ab
------aba
------abb
------abc
----ac
------aca
------acb
------acc
----ad
------ada
------adb
------adc
this works by having the print method calling itself and adjusting the indentation level.
The current node and level are printed.
if that node's list is non-null, then the print method is called for each node in the list and the process repeated, updating the level.
upon each return, the method starts where it left off as it continues to call itself and return.
This is a common process for walking thru hie-rarchical data sets and will work with an indeterminate amount of levels.
public static void print(MyNode node, int level) {
System.out.println("-".repeat(level*2) + node);
if (node.getNodeList() != null) {
for (MyNode n : node.getNodeList()) {
print(n, level+1);
}
}
}
I recommend you read up on recursive processes. In some cases you can also return values as you traverse the hierarchy.
To define a recursive method, you first need to identify your base cases and recursive cases. In this scenario, the base case is when the node passed for the printing is null while the recursive case is when there are still children to be printed.
Since I understand that your program might be a school exercise, I'll avoid discussing what could be or could be not a better implementation of your Node class. Definitely, using a List data structure from the Collections framework would have been a better choice instead of a fixed array of 100 elements, but I think your teacher would like to keep things simple at the beginning and you most likely haven't covered the Collections framework yet since you said you're still struggling with recursion (which is totally fine, we all have to start somewhere!). So, I'll leave your class implementation exactly how it is. I will just add few methods and some tweaks.
Here, I've implemented a solution to show you how your recursive print could work. Bear in mind that I've split the print implementation in two methods only to make its invocation easier for the client. In fact, a client should not be aware nor bothered with the internal implementation details of something to make it work.
//Test class
public class Test {
public static void main(String[] args) {
Node root = new Node(1, "test1", new Node[]{
new Node(2, "test2", new Node[]{
new Node(5, "test6", new Node[]{})
}),
new Node(3, "test3", new Node[]{
new Node(6, "test6", new Node[]{}),
new Node(7, "test7", new Node[]{
new Node(8, "test8", new Node[]{})
})
}),
new Node(4, "test4", new Node[]{})
});
root.print();
}
}
class Node {
int value;
String name;
Node parent;
int childrenCount;
Node[] children = new Node[100];
public Node(int value, String name) {
this.value = value;
this.name = name;
this.childrenCount = 0;
}
//Added second constructor only to ease the test
public Node(int value, String name, Node[] children) {
this.value = value;
this.name = name;
this.children = children;
this.childrenCount = getNumChildren(children);
}
public Node(String name) {
this.name = name;
}
//Fixed possible exception when added more than 100 elements
public boolean addChildren(Node node) {
if (childrenCount == this.children.length) {
return false;
}
this.children[childrenCount++] = node;
return true;
}
public void setParent(Node parent) {
this.parent = parent;
}
public boolean hasParent() {
return this.parent != null;
}
public int sumValue() {
int sum = 0;
sum += this.value;
for (int i = 0; i < childrenCount; i++) {
sum += children[i].value;
}
return sum;
}
//small utility method only to compute the effective number of children when an array is passed within the new constructor
public static int getNumChildren(Node[] children) {
int num = 0;
while (num < children.length && children[num] != null) {
num++;
}
return num;
}
//print method invoked by the client of the class
public void print() {
printRec(this, 0);
}
//recursive print
private void printRec(Node n, int numCall) {
//identifying the base case
if (n == null) {
return;
}
//Printing as many dahses as the depth of the current child node
for (int i = 1; i <= numCall; i++) {
System.out.print("--");
}
//printing the node info
System.out.println(n.name + " (" + n.value + ")");
//recursively invoking the print method for each child
for (int i = 0; i < n.childrenCount; i++) {
printRec(n.children[i], numCall + 1);
}
}
}
Here I just wanted to add a couple of side notes:
children is already the plural form of child. You don't need to call your array childrens.
Your previous implementation of the add method could have raised an ArraIndexOutOfBoundsException, if you had added more than 100 elements. Usually, when an operation could fail, the method should return a boolean to tell the client whether the operation succeeded or not.

Getting all possible paths in a tree structure

I need to loop in a tree to get all possible paths, the problem in my code that i get just the first path!
example:
In the figure, there are 2 paths t handle: 1-2-3-4-5-6 and 1-2-3-7-8 , but i couldn't get both, i have just retrieved 1-2-3-4-5-6 !
my code:
In main:
for (String key : synset.keySet()) { // looping in a hash of Concept and it's ID
System.out.println("\nConcept: " + key + " " + synset.get(key));
List<Concept> ancts = myOntology.getConceptAncestors(myOntology.getConceptFromConceptID(synset.get(key))); // this function retreives the root of any node.
for (int i = 0; i < ancts.size(); i++) {
System.out.print(ancts.get(i).getConceptId() + " # ");
System.out.print(getChilds(ancts.get(i).getConceptId()) + " -> "); // here, the recursive function is needed to navigate into childs..
}
System.out.println("");
}
Rec. function:
public static String getChilds(String conId)
{
List<Concept> childs = myOntology.getDirectChildren(myOntology.getConceptFromConceptID(conId)); // get all childs of a node
if(childs.size() > 0)
{
for (int i = 0; i < childs.size(); i++) {
System.out.print( childs.size() + " ~ " + childs.get(i).getConceptId() + " -> ");
return getChilds(childs.get(i).getConceptId());
}
}
else
return "NULL";
return "final";
}
I didn't really see enough of your code to use the classes that you have defined. So I went for writing my own working solution.
In the following code, the problem is solved using recursion:
public class TreeNode {
private String id;
private TreeNode parent;
private List<TreeNode> children;
public TreeNode(String id) {
this.id = id;
this.children = new LinkedList<>();
}
public void addChild(TreeNode child) {
this.children.add(child);
child.setParent(this);
}
public List<TreeNode> getChildren() {
return Collections.unmodifiableList(this.children);
}
private void setParent(TreeNode parent) {
this.parent = parent;
}
public TreeNode getParent() {
return this.parent;
}
public String getId() {
return this.id;
}
}
public class TreePaths {
private static List<List<TreeNode>> getPaths0(TreeNode pos) {
List<List<TreeNode>> retLists = new ArrayList<>();
if(pos.getChildren().size() == 0) {
List<TreeNode> leafList = new LinkedList<>();
leafList.add(pos);
retLists.add(leafList);
} else {
for (TreeNode node : pos.getChildren()) {
List<List<TreeNode>> nodeLists = getPaths0(node);
for (List<TreeNode> nodeList : nodeLists) {
nodeList.add(0, pos);
retLists.add(nodeList);
}
}
}
return retLists;
}
public static List<List<TreeNode>> getPaths(TreeNode head) {
if(head == null) {
return new ArrayList<>();
} else {
return getPaths0(head);
}
}
}
To use the above code, a tree must be constructed using the TreeNode class. Start off by creating a head TreeNode, then add child nodes to it as required. The head is then submitted to the TreePaths getPaths static function.
After getPaths checks for null, the internal getPaths0 function will be called. Here we follow a depth first approach by trying to get to all leaf nodes as soon as possible. Once a leaf node is found, a List only containing this leaf node will be created and returned inside the list collection. The parent of this leaf node will then be added to the beginning of the list, which will again be put into a list collection. This will happen for all children of the parent.
In the end, all possible paths will end up in a single structure. This function can be tested as follows:
public class TreePathsTest {
TreeNode[] nodes = new TreeNode[10];
#Before
public void init() {
int count = 0;
for(TreeNode child : nodes) {
nodes[count] = new TreeNode(String.valueOf(count));
count++;
}
}
/*
* 0 - 1 - 3
* - 4
* - 2 - 5
* - 6
* - 7 - 8
* - 9
*/
private void constructBasicTree() {
nodes[0].addChild(nodes[1]);
nodes[0].addChild(nodes[2]);
nodes[1].addChild(nodes[3]);
nodes[1].addChild(nodes[4]);
nodes[2].addChild(nodes[5]);
nodes[2].addChild(nodes[6]);
nodes[2].addChild(nodes[7]);
nodes[7].addChild(nodes[8]);
nodes[7].addChild(nodes[9]);
}
#Test
public void testPaths() {
constructBasicTree();
List<List<TreeNode>> lists = TreePaths.getPaths(nodes[0]);
for(List<TreeNode> list : lists) {
for(int count = 0; count < list.size(); count++) {
System.out.print(list.get(count).getId());
if(count != list.size() - 1) {
System.out.print("-");
}
}
System.out.println();
}
}
}
This will print out:
0-1-3
0-1-4
0-2-5
0-2-6
0-2-7-8
0-2-7-9
Note: The above is enough for manual testing, but the test function should be modified to do proper assertions for proper automated unit testing.
maybe this code segment in getChilds() exist problem:
for (int i = 0; i < childs.size(); i++) {
System.out.print( childs.size() + " ~ " + childs.get(i).getConceptId() + " -> ");
return getChilds(childs.get(i).getConceptId());
}
the for loop cant play a role, it always return getChilds(childs.get(0).getConceptId());
maybe this is not what you want.
One simple way.
All you need is a tree traversal and little bit of custom code.
Have a list called tempPath. you can take it as an argument or a global variable.
Do a tree traversal(eg. inorder). Whenever you are at a node add this to tempPath list at the end and when you are done with this node remove the node from the end of tempPath.
whenever you encounter a leaf, you have one full path from root to leaf which is contained in tempPath. you can either print or copy this list value into another data structure.

Using toString Method instead of Print method

How can I use the toString method, instead of my custom print method below, in my code? My current code's output is exactly what it is supposed to be, but my instructor wants me "to use toString and get same output". I am confused and do not know how to do it.
Here is my code:
public class LinkedListIntro {
//print method
public static void print(Node temp) {
System.out.print("[");
while (temp.getNext() != null) {
System.out.print(temp.getData() + ", ");
temp = temp.getNext();
}
System.out.println(temp.getData() + "]");
}
public static void main(String[] args) {
Node start = null;
Node temp = null;
for (int i = 1; i <= 5; i++) {
if (start == null) {
start = new Node(i);
temp = start;
} else {
temp.setNext(new Node(i));
temp = temp.getNext();
}
}
//3. printing data
print(start);
//4. removing 4
temp = start;
Node n = temp.getNext();
while (n.getNext() != null) {
if ((int) n.getData() == 4) {
temp.setNext(n.getNext());
n = null;
break;
}
temp = temp.getNext();
n = n.getNext();
}
//5. printing data again after removing 4
print(start);
//6. adding 100 between 1 and 2
temp = start;
Node n1 = temp.getNext();
while (n1.getNext() != null) {
if ((int) temp.getData() == 1) {
temp.setNext(new Node(100));
temp = temp.getNext();
temp.setNext(n1);
}
temp = temp.getNext();
n1 = n1.getNext();
}
//7. printing data again after adding 100
print(start);
//8. removing first node
temp = start;
start = start.getNext();
temp = null;
//printing data after removing 1st node
print(start);
//9. add 0 to beginning
temp = start;
start = new Node(0);
start.setNext(temp);
//printing the final data
print(start);
}
}
public class Node<E>
{
private E data;
private Node next;
public Node(E data) {
this.data = data;
this.next = null;
}
public E getData(){
return data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public String toString() {
return data.toString();
}
}
Use the code in you current print method to build an output string in toString() method of Node. After that, print can just pass the Node temp parameter to System.out.print(), cause it uses toString() internally.
public static void print(Node temp) { //irrelevant method by now
System.out.print(temp);
}
public class Node<E>{
private E data;
private Node next;
//...
public String toString() {
String ouput = "";
Node node = this;
while(node.getNext() != null) {
output += node.getData() +", ";
node = node.getNext();
}
return ouput;
}
}
The toString() methods returns a "string representation" of the object, which means that it returns information about an object as a string. toString() is overridden by the each class that implements it. The global superclass (Object) has a .toString() method but it usually doesn't return the information we want. I think he wants you to make your own toString() that returns a string representation of the Node object. Then you can call System.out.print() on this string to display it.
I would create a toString method which returns a string in LinkedListIntro class which would do what your print method is doing. But instead of printing it would keep appending the value to a string and return the string
I believe what your instructor means is that in the class's toString(), you have to return a string for the entire linked list, not just for the current node.
The trick is that to do it properly, you'll probably need to do it either recursively or with a helper variable. You'll basically need to prepend the current item's data's toString() result to whatever you get from next.
Once you do that, you won't need the print function.
I think your instructor wants you to implement the method toString() in your class.
Every class your create is children of Object class, since this is the superclass for every object. This class has some methods like toString(). In your new class, you should override the method toString(). This method must return a String, which should be a description or some helpfull text about every object of this class.
The purpose of this is that if your new class is cast as Object, when you call the toString() method, it gets the right representation of the new class.
You have a class:
public class SomeClass {
public String text;
public SomeClass() {
text = "hello world";
}
#Override public String toString() {
return (text);
}
}
And in your main function:
public static void main(String[] args) {
//new object of type SomeClass
SomeClass someClass = new SomeClass();
System.out.println(someClass.toString());
//casting it to superclass Object
Object someClass_cast = (Object)someClass;
System.out.println(someClass_cast.toString());
}
Your output will be:
hello world
hello world
I hope this can help you.

Null pointer Exception in CompareTo method

Structure of my class:
public class Priorityy implement Comparable {
public int compareTo(Object pe) {
Priorityy p = (Priorityy) pe;
if (this.key < p.key) {
return 1;
} else if (this.key > p.key) {
return -1;
} else {
return 0;
}
}
}
Th problem is that p.key is always null, why exactly is that? I have my array initialized with elements in it but it always throws NullPointerException whenever I try Arrays.sort(arr).
How can I fix this?
Edit: Here is the complete code and print did print the elements of array arr:
import java.util.Arrays;
class Priorityy implements Comparable {
int size;
int front = 0;
int rear = 0;
static Priorityy[] arr = new Priorityy[3];
int key;
String value;
public Priorityy(int key, String value) {
this.key = key;
this.value = value;
insert();
}
public void insert() {
arr[front] = this;
System.out.println(arr[front].value);
while (front + 1 != 3) {
front = front + 1;
}
}
public Priorityy remove() {
Priorityy x = arr[front];
front = front - 1;
return x;
}
public int compareTo(Object pe) {
Priorityy p = (Priorityy) pe;
if (this.key < p.key) {
System.out.println(p.key);
return 1;
} else if (this.key > p.key) {
System.out.println("3");
return -1;
} else {
System.out.println("4");
return 0;
}
}
public static void main(String... s) {
new Priorityy(10, "Watch");
new Priorityy(40, "Laptop");
new Priorityy(60, "Wallet");
Arrays.sort(arr);
for (Priorityy element : arr) {
System.out.println(element.key);
System.out.println(element.value);
}
}
}
As per your code
Priorityy p = (Priorityy)pe;
^^ ---------- this is null
You have null object in the array. Handle null object gracefully.
For example
if(pe instanceof Priorityy){ // return false for null object
// your code goes here
}
Better use Generic Comparable and use Integer.compare(int,int) to compare two int values.
class Priorityy implements Comparable<Priorityy> {
public int compareTo(Priorityy pe) {
if (pe != null) {
return Integer.compare(this.key, pe.key);
} else {
// return what ever if pe is null
}
}
}
You're putting things into your array in a really strange manner.
But given that, the problem is that you're not using a static field to store the next position to insert an element into, so the next time you create an instance of Priorityy, the field first contains the value zero again. So you're inserting all three objects into element zero of the array.
Change one line of your code and it will work:
int front = 0;
To:
static int front = 0;
I don't see where you are using size and rear but you probably want these to be static too.
One other suggestion: Java has a nice short syntax for increasing or decreasing the value of a variable by one using the ++ or -- operator, so you can shorten things by saying:
front++;
instead of
front = front + 1;
(and front-- instead of front = front - 1)

Categories

Resources