I am a beginner in java and I am currently working Nodes. I was wondering if there was a way to show the content of a list without having to use .getNext method, because once I use it, it removes the element that was on the Node well literally removes the Node on top. What I am trying to do in this code is using input to store two String elements in the new two Nodes then using the method proveTitle to prove that those elements are on the list. Once I do that I make sure that elements are still intact and use the toString method to check the list. Note that in the class of Book for some strange reason the
T isnt showing besides the class and the implemented class if I put the <> around it.
Heres the code:
myNode class:
public class myNode<T>
{
private T data;
private myNode next;
public myNode(T _data)
{
data = _data;
}
public myNode(T _data, myNode _next)
{
data = _data;
next = _next;
}
public T getData()
{
return data;
}
public void setData(T _data)
{
data = _data;
}
public myNode getNext()
{
return next;
}
public void setNext(myNode _next)
{
next = _next;
}
}
Interface class:
public interface myInterface<T>
{
public void pushTitle(T data);
public T pop();
public T peek();
public String toString();
public boolean isEmpty();
public int size();
public myNode getNode();
}
Book class, which contains the methods
public class Book implements myInterface
{
private int count;
private T author;
private T title;
private int stock;
private myNode<T> top;
public Book()
{
count = 0;
top = null;
}
#Override
public myNode getNode()
{
return top;
}
#Override
public void pushTitle(T title)
{
myNode<T> current = new myNode<>(title, top);
current.setNext(top);
top = current;
count++;
}
public void proveTitle(T title)
{
T result;
myNode<T> current = top;
if(title.equals(current.getData()))
{
result = current.getData();
System.out.println("The title " + "'" + result + "'" + " exist.");
top = top.getNext();
}
}
#Override
public T pop()
{
T result;
if(count == 0 || top == null )
{
System.out.println("List is empty");
}
System.out.println("The element on top is:" + top.getData());
result = top.getData();
top = top.getNext();
count--;
return result;
}
#Override
public T peek()
{
System.out.println("Element on top is: " + top.getData());
return top.getData();
}
#Override
public boolean isEmpty()
{
if(top == null)
{
System.out.println("The list is empty");
}
else
{
System.out.println("The list is not empty." + "It has" + count + "elements");
}
return top == null;
}
#Override
public int size()
{
System.out.println("The size of the list is" + count);
return count;
}
#Override
public String toString()
{
String result = "";
myNode current = top;
System.out.println("Top");
while(current != null)
{
result += ("[" + current.getData() + "]\n");
current = current.getNext();
}
return result + "Bottom";
}
}
main class:
package node;
import java.util.Scanner;
public class myDriver
{
public static void main(String[]args)
{
Scanner input = new Scanner(System.in);
Book<String> title = new Book<>();
myNode<String> current;
current = title.getNode();
String push;
String push2;
System.out.println("Enter title of book 1");
push = input.nextLine();
title.pushTitle(push);
System.out.println("Enter title of book 2");
push2 = input.nextLine();
title.pushTitle(push2);
title.proveTitle(push);
title.proveTitle(push2);
System.out.println(title.toString());
}
}
Output:
run:
Enter title of book 1
Tiger
Enter title of book 2
crossed
The title 'crossed' exist.
Top
[Tiger]
Bottom
BUILD SUCCESSFUL (total time: 7 seconds)
You seem to be trying to implement a List using a Stack. These are very different data structures. What you are trying to do is very easy in a List. In a Stack it requires that you have a second stack. As you pop each object off the current stack, you push it onto the second stack.
If order doesn't matter, you can do this once and switch to using the second stack. If order does matter, you will have to reverse the process to get back your original stack.
Also note that the better approach would probably be to just use a List.
Related
Before all, here is a Minimal Working Example of my code on GitHub:
https://github.com/rmwesley/DancingLinks_MWE
I've been trying to implement the Dancing Links' algorithm by D. Knuth to solve the Exact Cover problem.
The code works. Problem is, I want to implement an Iterator.
In fact, the Iterator works for Node.java.
But not for Column.java, as I will further detail.
I've tried completely refactoring the code and doing some crazy modifications, but to no avail.
I left some of my best trials as commented lines of code.
These were the least garbagey ones.
My current design is as follows:
Given a problem matrix, I aimed at constructing the main data structure with 4-way nodes.
So first I implemented Node.java, a 4-way circularly linked data structure.
Then I extend Node.java in Column.java, which is the "backbone" of the structure.
Column elements then make up the main row.
Rows of Nodes are then linked with the rest of the structure with .addRow().
That is, new rows come below the last added row and above the column. Remember, circular.
See the schematics in D. Knuth's paper: https://arxiv.org/abs/cs/0011047.
With this, the full structure can be initialized from a given problem matrix.
"this" in Column serves as the head itself, so no elements are added above or below it.
Here is my source code:
Node.java
public class Node implements Iterable<Node> {
private Node upNode;
private Node downNode;
private Node leftNode;
private Node rightNode;
private Column column;
public Node() {
upNode = this;
downNode = this;
leftNode = this;
rightNode = this;
column = null;
}
#Override
public String toString() {
String str = this.column.getSize() + " ";
for (Node node : this){
str += node.column.getSize() + " ";
}
return str;
}
#Override
public java.util.Iterator<Node> iterator(){
Node currNode = this;
return new NodeIter(this);
}
public Column getColumn(){
return this.column;
}
public void setColumn(Column column){
this.column = column;
}
public Node getR(){
return this.rightNode;
}
public Node getD(){
return this.downNode;
}
public Node getL(){
return this.leftNode;
}
public Node getU(){
return this.upNode;
}
void removeHoriz() {
this.rightNode.leftNode = this.leftNode;
this.leftNode.rightNode = this.rightNode;
}
void removeVert() {
this.downNode.upNode = this.upNode;
this.upNode.downNode = this.downNode;
}
void restoreVert() {
this.downNode.upNode = this;
this.upNode.downNode = this;
}
void restoreHoriz() {
this.rightNode.leftNode = this;
this.leftNode.rightNode = this;
}
//Create an horizontal link between nodes
public void linkD(Node other) {
this.downNode = other;
other.upNode = this;
}
//Create a vertical link between nodes
public void linkR(Node other) {
this.rightNode = other;
other.leftNode = this;
}
void addHoriz(Node other) {
other.rightNode = this.rightNode;
other.leftNode = this;
}
void addVert(Node other) {
other.downNode = this.downNode;
other.upNode = this;
}
}
Column.java
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
//public class Column extends Node implements Iterable<Column>{
public class Column extends Node {
private int size;
private String name;
public Column() {
super();
this.setColumn(this);
size = 0;
name = new String();
}
public Column(int length) {
this();
Column currColumn = this;
for(int i = 0; i < length; i++){
currColumn.setName("" + i);
Column nextColumn = new Column();
currColumn.linkR(nextColumn);
currColumn = nextColumn;
}
currColumn.linkR(this);
}
public void addRow(int[] vector) throws Exception {
Column currColumn = this;
Node firstNode = new Node();
Node currNode = firstNode;
Node prevNode = currNode;
for(int index=0; index < vector.length; index++){
currColumn = currColumn.getR();
if(vector[index] == 0) continue;
currColumn.increment();
currColumn.getU().linkD(currNode);
currNode.linkD(currColumn);
currNode.setColumn(currColumn);
prevNode = currNode;
currNode = new Node();
prevNode.linkR(currNode);
}
currColumn = currColumn.getR();
prevNode.linkR(firstNode);
if(currColumn != this){
throw new Exception("Differ in length");
}
}
public Column(int[][] matrix) throws Exception {
this(matrix[0].length);
for(int i = 0; i < matrix.length; i++){
this.addRow(matrix[i]);
}
}
#Override
public Column getR(){
return (Column) super.getR();
}
#Override
public Column getL(){
return (Column) super.getL();
}
#Override
public String toString(){
String str = "";
//for (Column currColumn : this) str += currColumn.getSize() + " ";
for (Column currColumn = this.getR();
currColumn != this;
currColumn = currColumn.getR()){
str += currColumn.getSize() + " ";
}
return str;
}
public String getName(){
return this.name;
}
public int getSize(){
return this.size;
}
public void setSize(int size){
this.size = size;
}
public void setName(String name){
this.name = name;
}
public void increment(){
this.size++;
}
public void decrement(){
this.size--;
}
/*
#Override
public Iterator<Column> iterator(){
return new Iterator<Column>(){
private Column currNode = Column.this;
#Override
public boolean hasNext(){
return currNode.getR() != Column.this;
}
#Override
public Column next(){
if (!hasNext()) throw new NoSuchElementException();
currNode = currNode.getR();
return currNode;
}
};
}
*/
}
NodeIter.java
public class NodeIter implements java.util.Iterator<Node>{
private Node head;
private Node current;
public NodeIter(Node node){
this.head = this.current = node;
}
#Override
public boolean hasNext(){
return current.getR() != head;
}
#Override
public Node next(){
if (!hasNext()) throw new java.util.NoSuchElementException();
current = current.getR();
return current;
}
}
Commented lines give these errors when uncommented:
src/Column.java:5: error: Iterable cannot be inherited with different arguments: <Column> and <Node>
public class Column extends Node implements Iterable<Column>{
^
src/Column.java:111: error: iterator() in Column cannot implement iterator() in Iterable
public Iterator<Column> iterator(){
^
return type Iterator<Column> is not compatible with Iterator<Node>
where T is a type-variable:
T extends Object declared in interface Iterable
src/Column.java:76: error: incompatible types: Node cannot be converted to Column
for (Column currColumn : this) str += currColumn.getSize() + " ";
How do I make Column.java iterable?
I've been coding in Java recently, but without carefully considering design patterns.
So I fully believe I am suffering the consequences of bad code design.
Should I make some abstract class or make use of some Generic Type?
Like Node and Column, just so I can implement Iterable.
Am I wrong?
Does anyone have any pointers?
Tried using generics and overriding .iterator() method with different return types in Column.java.
Even tried using completely different class structures.
The Node class has an implementation of the Iterable interface in the form of one method:
#Override
public java.util.Iterator<Node> iterator(){
Node currNode = this;
return new NodeIter(this);
}
(BTW the first line of this method is not doing anything useful)
You are trying to make Node's subclass Column implement Iterable, meaning you want to add an overriding method like this:
#Override
public Iterator<Column> iterator()
Such an override which only differs in return type is not allowed in Java, hence the compilation error.
The fundamental problem is that, since Node is an Iterable, all its subclasses will also be an Iterable due to inheritance.
I guess you would like to write code like this:
for(Node n : node) {
for(Column c : n.getColumn()) {
c.increment();
}
}
Currently I think you could do this:
for(Node n : node) {
for(Node c : n.getColumn()) {
((Column) c).increment();
}
}
Where you are casting the iterand to Column in order to access Column methods.
I do think the design is weird when I read this for instance:
public Column() {
super();
this.setColumn(this);
eh? So a Column is a Node which has a column field? Seems like the design is conflicted about whether a Column is-a Node, or a Node has-a Column... I feel like your iterable problem will magically disappear once you figure that out.
EDIT: I don't fully grasp the algorithm and data structure yet (although I read a bit about it). From what I've understood I think you should create something like the following structure:
class Matrix {
Column[] columns;
Matrix(int[][] input) {
// init Columns
}
}
class Column {
String name;
int size;
Node firstNode;
}
class Node {
Node up;
Node down;
Node left;
Node right;
}
And avoid sub classing, it's usually not needed. Better to work with interfaces and collaborators.
I'm doing a dictionary system for my school assignment. The idea that I'm trying to do is to store every single word and its definitions in a node and searching them using a binary search tree.
But there has an issue that occurred. When I add a word and definition in a node in the linked list, the wordList() method returns the last node that I've entered. I think I am having trouble implementing and linking the nodes. Could you please help me? (Note: Vocab is my test class)
public class Node {
private static String word;
private static String definition;
private Node link;
public Node() {
link = null;
word = null;
}
public Node(String newWord) {
setWord(newWord);
link = null;
}
public Node(String newWord, Node linkValue) {
setWord(newWord);
link = linkValue;
}
public Node(String newWord, String newDefinition, Node linkValue) {
setWord(newWord, newDefinition);
link = linkValue;
}
public Node(String newWord, String newDefinition) {
setWord(newWord, newDefinition);
}
#Override
public String toString() {
return "Node [word=" + word + ", link=" + link + "]";
}
public static String getDefinition() {
return definition;
}
public void setDefinition(String definition) {
this.definition = definition;
}
public static String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public void setWord(String word, String definition) {
this.word = word;
this.definition = definition;
}
public Node getLink() {
return link;
}
public void setLink(Node link) {
this.link = link;
}
}
public class LinkedList {
protected static Node first;
private Node last;
public LinkedList() {
super();
this.first = null;
this.last = null;
}
public LinkedList(String wordName, String wordDefinition, Node first2) {
// TODO Auto-generated constructor stub
}
public boolean isEmpty() {
return(first == null);
}
public void insert(String newWord, String newDefinition) {
if(isEmpty()) {
first= last= new Node(newWord, newDefinition, first);
}
else {
first = new Node(newWord, newDefinition, first);
}
}
public void wordList() {
Node current = first;
while(current != null) {
System.out.println(current.getWord());
current = current.getLink();
}
}
public static Node getFirst() {
return first;
}
public void setFirst(Node first) {
this.first = first;
}
public Node getLast() {
return last;
}
public void setLast(Node last) {
this.last = last;
}
}
public class Vocab {
public static void main(String[] args) {
LinkedList dictionary = new LinkedList();
Node a = new Node("Assembly","A unit of fitted parts that naje yo a mechanism or machine, such as the headstock assemble of a lathe.");
dictionary.setFirst(a);
Node b = new Node("Boil","Agitation of a bath of metal caused by the liberation of a gas beneath its surface.");
a.setLink(b);
b.setLink(null);
dictionary.wordList();
}
}
If you want to use your LinkedList, use its methods rather than making the manipulations by hand:
LinkedList dictionary = new LinkedList();
// Node a = new Node("Assembly","A unit of fitted parts that naje yo a mechanism or machine, such as the headstock assemble of a lathe.");
dictionary.setFirst(a);
//Node b = new Node("Boil","Agitation of a bath of metal caused by the liberation of a gas beneath its surface.");
//a.setLink(b);
//b.setLink(null);
dictionary.wordList();
In the code above I have commented out all lines of code that go one level too deep. On the usage side you should never care that the Node class is used internally.
Have a look at LinkedList methods that will work for you. Then try to think of why when you are not using them you never alter the internal properties of the list, thus leaving it broken an half setup.
EDIT: By the way consider removing the setFirst and setLast methods that accept Node instances. They are only confusing you and should have never been there.
public static void main (String[] args)
{
Student st1 = new Student("Adams", 3.6, 26);
Student st2 = new Student("Jones", 2.1, 29);
Student st3 = new Student("Marcus", 4.0, 53);
System.out.println("Testing non-recursive code");
LinkedListStud LL = new LinkedListStud();
//checks if linked list is empty
System.out.println("Linked list is empty?: " + LL.isEmpty());
//adds students to the linked list from the front
LL.addFront(st3);
LL.addFront(st2);
LL.addFront(st1);
//adds students to the linked list from the back
LL.addTail(st1);
LL.addTail(st2);
LL.addTail(st3);
//prints linked list non-recursively
LL.printLL();
System.out.println("Linked list is empty?: " + LL.isEmpty());
}
this is my testing method ^ as you can see I am filling my list with student objects. The printLL() method shows all 6 objects are in fact in the array.
public boolean isEmpty()
{
Boolean e;
if (list==null)
return e=true;
else
return e=false;
}
This is my isEmpty() method. The parameters and data type is specified by my professor. For some reason my list always equals null even though it should contain 6 objects the second time I use the method. What am I missing?
My entire linked list class
public class LinkedListStud
{
private Node list;
public LinkedListStud()
{
list = null;
}
public void addFront(Student s)
{
Node oneNode = new Node(s);
oneNode.next=list;
list=oneNode;
}
public void addTail(Student s)
{
Node current;
Node oneNode = new Node(s);
if (list==null)
list=oneNode;
else
{
current=list;
while (current.next != null)
current=current.next;
current.next=oneNode;
}
}
public boolean isEmpty()
{
Boolean e=true;
if (list!=null)
return false;
else
return e;
}
public Student bestStudent()
{
Student bestStudent=list.data;
while (list.next!=null)
{
if (list.next.data.getGpa()>list.data.getGpa())
{
Student temp = list.data;
list.data=list.next.data;
list.next.data=temp;
}
list=list.next;
}
return bestStudent;
}
public void printLL()
{
while (list!=null)
{
System.out.println(list.data);
list=list.next;
}
}
public void printLLRec(Node list)
{
if (list!=null)
{
System.out.println(list.data);
printLLRec(list.next);
}
}
Student bestStudRec(Node list)
{
Student bestStudent = list.data;
if (list!=null)
{
if (list.next.data.getGpa()>list.data.getGpa())
{
bestStudent=list.next.data;
bestStudRec(list.next);
}
}
return bestStudent;
}
private class Node
{
public Student data;
public Node next;
public Node(Student s)
{
data=s;
next=null;
}
public String toString()
{
return "" + data;
}
}
}
Problem is here:
public void printLL()
{
while (list!=null)
{
System.out.println(list.data);
list=list.next;
}
}
You replace list variable with nested list until it becomes null. Last iteration there set your LL.list to null, then while checks it and goes out. If you modify while like:
public void printLL()
{
while (list!=null)
{
System.out.println(list.data);
if (list.next == null) break;
list=list.next;
}
}
you will get what you need, but your root LL will have replaced value from last Node.
Following on from #Vadim 's answer, if you want to print it out without changing the internal list, you can introduce a local variable.
public void printLL()
{
Node temp = list;
while (temp!=null)
{
System.out.println(temp.data);
temp=temp.next;
}
}
I'm trying to write code in a way that it is object oriented. In this particular case I want to keep track of the minimum value of my stack in O(1) time. I know how to do it, the idea of it, well my idea of it, which is to have another stack that keeps track of the minimum value for every push and pop.
I've nested every class inside of the program class which is called minStack, which doesn't seem like the right thing to do however when I create a instance of minStack and call its variables it works out fine for a regular stack. I created a class that extends a Stack called StackWithMin but I don't know how to call its values. Should I create a new instance of a StackWithMin? If so how would i do it? I did it at the end of the code above the main function, but peek() always returns null
class minStack {
public class Stack {
Node top;
Object min = null;
Object pop() {
if(top != null) {
Object item = top.getData();
top = top.getNext();
return item;
}
return null;
}
void push(Object item) {
if(min == null) {
min = item;
}
if((int)item < (int)min) {
min = item;
}
Node pushed = new Node(item, top);
top = pushed;
}
Object peek() {
if(top == null) {
//System.out.println("Its null or stack is empty");
return null;
}
return top.getData();
}
Object minimumValue() {
if(min == null) {
return null;
}
return (int)min;
}
}
public class Node {
Object data;
Node next;
public Node(Object data) {
this.data = data;
this.next = null;
}
public Node(Object data, Node next) {
this.data = data;
this.next = next;
}
public void setNext(Node n) {
next = n;
}
public Node getNext() {
return next;
}
public void setData(Object d) {
data = d;
}
public Object getData() {
return data;
}
}
public class StackWithMin extends Stack {
Stack s2;
public StackWithMin() {
s2 = new Stack();
}
public void push(Object value) {
if((int)value <= (int)min()) {
s2.push(value);
}
super.push(value);
}
public Object pop() {
Object value = super.pop();
if((int)value == (int)min()) {
s2.pop();
}
return value;
}
public Object min() {
if(s2.top == null) {
return null;
}
else {
return s2.peek();
}
}
}
Stack testStack = new Stack();
StackWithMin stackMin = new StackWithMin();
public static void main(String[] args) {
minStack mStack = new minStack();
//StackWithMin stackMin = new StackWithMin();
mStack.testStack.push(3);
mStack.testStack.push(5);
mStack.testStack.push(2);
mStack.stackMin.push(2);
mStack.stackMin.push(4);
mStack.stackMin.push(1);
System.out.println(mStack.testStack.peek());
System.out.println(mStack.stackMin.peek());
mStack.testStack.pop();
}
}
I would suggest to create generic interface Stack like this one
interface Stack<T> {
void push(T item);
T pop();
T peek();
}
Generics add stability to your code by making more of your bugs
detectable at compile time.
See more about generics here.
Then implement this interface in a common way. All implementation details will be hidden inside of this class (your Node class for example). Here is the code (it is just to show the idea, if you want to use it you need to improve it with exception handling for example). Note that class Node is now also generic.
class SimpleStack<T> implements Stack<T> {
private class Node<T> { ... }
private Node<T> root = null;
public void push(T item) {
if (root == null) {
root = new Node<T>(item);
} else {
Node<T> node = new Node<T>(item, root);
root = node;
}
}
public T pop() {
if (root != null) {
T data = root.getData();
root = root.getNext();
return data;
} else {
return null;
}
}
public T peek() {
if (root != null) {
return root.getData();
} else {
return null;
}
}
}
Now we get to the part with stored minimum value. We can extend our SimpleStack class and add field with another SimpleStack. However I think this is better to make another implementation of the Stack and store two stacks for values and for minimums. The example is below. I have generalize the class that now uses Comparator to compare object, so you can use any other object types.
class StackWithComparator<T> implements Stack<T> {
private Comparator<T> comparator;
private SimpleStack<T> mins = new SimpleStack<>();
private SimpleStack<T> data = new SimpleStack<>();
public StackWithComparator(Comparator<T> comparator) {
this.comparator = comparator;
}
public void push(T item) {
data.push(item);
if (mins.peek() == null || comparator.compare(mins.peek(), item) >= 0) {
mins.push(item);
} else {
mins.push(mins.peek());
}
}
public T pop() {
mins.pop();
return data.pop();
}
public T peek() {
return data.peek();
}
public T min() {
return mins.peek();
}
}
Now you can use both implementations like so
SimpleStack<Integer> s1 = new SimpleStack<>();
s1.push(1);
s1.push(2);
s1.push(3);
System.out.println(s1.pop()); // print 3
System.out.println(s1.pop()); // print 2
System.out.println(s1.pop()); // print 1
StackWithComparator<Integer> s2 = new StackWithComparator<>(new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return Integer.compare(o1, o2);
}
});
s2.push(1);
s2.push(2);
s2.push(3);
s2.push(0);
s2.push(4);
System.out.println(s2.min() + " " + s2.pop()); // print 0 4
System.out.println(s2.min() + " " + s2.pop()); // print 0 0
System.out.println(s2.min() + " " + s2.pop()); // print 1 3
System.out.println(s2.min() + " " + s2.pop()); // print 1 2
System.out.println(s2.min() + " " + s2.pop()); // print 1 1
I was studying about hashset in java and for that I am writing creating my own hashset which will double its size everytimme the threshold value is reached..here I am keeping the threshold as 0.75 of original size . However my code is running into an infinite loop. I tried debugging it but was not able to find my error...
here is the code
package drafta;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class HashSet
{
private Node[] buckets;
private int currentSize;
private int current;
public HashSet(int bucketsLength)
{
buckets=new Node[bucketsLength];
currentSize=0;
}
public boolean contains(Object x)
{
return false;
// don't implement for the draft
}
public boolean add(Object x)
{
int key=gethashcode(x);
Node node = buckets[key];
while(node!=null){
if(node.data.equals(x)){
return false;
}
}
if(buckets[current]==null){
node = new Node(x);
current=key;
buckets[key]=node;
currentSize++;
}else{
node = new Node(x);
node.next=buckets[current];
current=key;
buckets[key]=node;
currentSize++;
}
System.out.println("add successful "+ x);
System.out.println(" size "+currentSize+" rehash "+buckets.length*0.75);
if(currentSize>(buckets.length*0.75)){
rehash();
}
return true;
}
private void rehash() {
Node temp=buckets[current];
Object s[]=new Object[buckets.length];
buckets=new Node[2*buckets.length];
currentSize=0;
int i=0;
while(temp!=null){
s[i]=temp.data;
temp=temp.next;
i++;
}
while(i>0){
add(s[--i]);
}
}
public boolean remove(Object x)
{
return false;
// don't implement for draft
}
public int gethashcode(Object x){
int hc = x.hashCode();
if(hc<0)
hc=-hc;
return (hc%buckets.length);
}
public Iterator<Object> iterator()
{
Iterator <Object> i=new HashSetIterator();
return i;
//
}
public int size()
{
return currentSize;
//
}
private void resize(int newLength)
{
}
public int getlength()
{
return buckets.length;
//
}
class Node
{
public Object data;
public Node next;
public Node(Object x) {
data=x;
}
public String toString(){
return data.toString();
}
}
class HashSetIterator implements Iterator<Object>
{
private int bucket=0;
private Node currentnode;
public HashSetIterator()
{
currentnode=buckets[current];
}
public boolean hasNext()
{
if(currentnode.next!=null)
return true;
else
return false;
//
}
public Object next()
{
return currentnode.next;
//
}
#Override
public void remove() {
currentnode.next=currentnode.next.next;
}
}
}
this is the main class which I am using to test my code
package drafta;
import java.util.Iterator;
public class HashSetTester
{
public static void main(String[] args)
{
HashSet names = new HashSet(5);
names.add("Harry");
names.add("Sue");
names.add("Nina");
System.out.println(names.size() + " " + names.getlength());
names.add("Susannah");
System.out.println(names.size() + " " + names.getlength());
System.out.println();
names.add("Larry");
names.add("Juliet");
names.add("Katherine");
names.add("Romeo");
names.add("Maria");
System.out.println(names.size() + " " + names.getlength());
names.add("Ann");
names.add("Taylor");
System.out.println(names.size() + " " + names.getlength());
}
}
can someone please point out my mistake..the code is going into infintie loop when it calls rehash for second time..first time it goes through correctly...
You arn't changing any conditions in your while loop in the add method - so there is no reason for it to break out.
while(node!=null){
if(node.data.equals(x)){
return false;
}
}
You will continue looping until the node is null (which never gets set) or the node data ever equals x, but the data value also never gets set.