Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 09-29-2008, 12:57 AM   PM User | #1
unc123w
New to the CF scene

 
Join Date: Sep 2008
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
unc123w is an unknown quantity at this point
LinkedList help

I'm working on a Linked List class and need a "removeAll" method that will iterate through a list remove each instance of x, then return a new list with these objects remove.

Code:
public void removeAll(T x) {

	 java.util.Iterator<T> it = this.iterator();
	 while(it.hasNext()) {
		 LinkedList l = new LinkedList();
		 T object = x;
		 l.remove(x);
		 System.out.println(it.next());
		 System.out.println(l);
		
		 
	 }
	
}
In the main method, I've got this to add numbers to the list then remove each instance of 3.

Code:
ExtendedLinkedList<Integer> list3 = new ExtendedLinkedList<Integer>();
list3.add(3);
list3.add(4);
list3.add(6);
list3.add(3);
list3.add(9);
list3.removeAll(3);
I feel like I'm close, but the output I'm getting is the actual list, and an empty list.



3
[]
4
[]
6
[]
3
[]
9
[]
unc123w is offline   Reply With Quote
Old 09-29-2008, 01:47 AM   PM User | #2
shadowmaniac
Regular Coder

 
Join Date: Apr 2005
Location: Ohio
Posts: 254
Thanks: 1
Thanked 63 Times in 63 Posts
shadowmaniac is an unknown quantity at this point
Quote:
Originally Posted by unc123w View Post
Code:
public void removeAll(T x) {
	 java.util.Iterator<T> it = this.iterator();
	 while(it.hasNext()) {
		 LinkedList l = new LinkedList(); // list is empty and not initialized
		 T object = x;
		 l.remove(x);
		 System.out.println(it.next());
		 System.out.println(l);
	 }
}
The reason you're getting an empty list as output is because every time you go to the while loop, you create an empty list "l". You want to create the actual list outside the loop and then initialize it to the values of list3. Basically something like this:

Code:
public void removeAll(T x) {
	 java.util.Iterator<T> it = this.iterator();
	 LinkedList l = new LinkedList();
         l.addAll(<<<<reference to list3>>>>) //initialize l
	 while(it.hasNext()) {
		 T object = x;
		 l.remove(x);
		 System.out.println(it.next());
		 System.out.println(l);
	 }
}
Don't hold me up on the validity of the above code though. Still, my "observations" should be good.
shadowmaniac is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 08:48 PM.


Advertisement
Log in to turn off these ads.