2 Replies - 1766 Views - Last Post: 25 March 2012 - 10:39 AM Rate Topic: -----

#1 Wangagat  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 17-February 12

Creating own HashSet class... implementing own iterator

Posted 25 March 2012 - 03:55 AM

Hi everyone,

I am trying to implement my own hashSet class, and am having trouble implementing an iterator for it... when I try using the iterator in a main, hasNext() always comes up as false so it it never enters the loop to display the elements of the set. I'm not sure what is wrong. Any help would be appreciated!

Thanks!


       private class Node {
		Word value;
		Node next = null;
		
		public Node(Word word) {value = word;}
		public String toString() {return value.toString();}
	}

	class WordIterator implements Iterator<Word> {
		
		private Node next;
		private int index = 0;
		
		public Word next() {
			Node element = next;
			if (element == null)
				throw new NoSuchElementException();
			if ((next = element.next) == null) {
				Node[] temp = buckets;
				while (index < temp.length && (next = temp[index++]) == null)
					  ;	
			}
			return element.value;
		}
	 		
		public boolean hasNext() {
			return (next != null);
		}
	
		public void remove() { throw new RuntimeException("remove() is not implemented");}
	}


Is This A Good Question/Topic? 0
  • +

Replies To: Creating own HashSet class... implementing own iterator

#2 Sheph  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 432
  • View blog
  • Posts: 1,020
  • Joined: 12-October 11

Re: Creating own HashSet class... implementing own iterator

Posted 25 March 2012 - 08:34 AM

Where is your main class? How do you call this code? Specifically how add elements to the set?
Was This Post Helpful? 0
  • +
  • -

#3 Wangagat  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 14
  • Joined: 17-February 12

Re: Creating own HashSet class... implementing own iterator

Posted 25 March 2012 - 10:39 AM

here's my main:


                public static void main(String[] args) {
		HashWordSet hashSet = new HashWordSet();
		try {
			File file = new File ("src/words.txt");
			Scanner scan = new Scanner(file);
		
			while (scan.hasNext()) {
				Word temp = new Word(scan.next());
				hashSet.add(temp);
				treeSet.add(temp);
			}
		}
		catch ( IOException e ) {e.printStackTrace ();}
                Iterator<Word> iterator = treeSet.iterator();
		
		while (iterator.hasNext())
			System.out.println(iterator.next());
	}


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1