Some Eclipse Foundation services are deprecated, or will be soon. Please ensure you've read this important communication.

Bug 355283

Summary: [extract local] Extract local variable generates incorrect code
Product: [Eclipse Project] JDT Reporter: Robin Rosenberg <robin.rosenberg>
Component: UIAssignee: JDT-UI-Inbox <jdt-ui-inbox>
Status: CLOSED DUPLICATE QA Contact:
Severity: normal    
Priority: P3 CC: deepakazad, Olivier_Thomann
Version: 3.7   
Target Milestone: ---   
Hardware: PC   
OS: Mac OS X - Carbon (unsup.)   
Whiteboard:

Description Robin Rosenberg CLA 2011-08-19 19:21:28 EDT
Here is some old "legacy" code. I was using the refactoring tool that I've trusted very much
until now.  Start with the following code, then elect the last occurrence of  "" + val

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


public class LegacyCode {

	public static void ugly() {
		List<Long> in = new ArrayList<Long>();
		Map<String,Long> out = new HashMap<String,Long>();
		Iterator<Long> it = null;
		it = in.iterator();
		Long val = null;
		// Refactoring inserts new variable here: String key = "" + val;
		while (it.hasNext()) {
			val = it.next();
			if (!out.containsKey("" + val))
				out.put("" + val, val);
		}
		it = in.iterator();
		while (it.hasNext()) {
			val = it.next();
                        // I would expect a local variable to be created here
			if (!out.containsKey("" + val))
				out.put("" + val, val);
		}
 	}
}

After:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


public class LegacyCode {

	public static void ugly() {
		List<Long> in = new ArrayList<Long>();
		Map<String,Long> out = new HashMap<String,Long>();
		Iterator<Long> it = null;
		it = in.iterator();
		Long val = null;
		String key = "" + val; // Wrong place
		while (it.hasNext()) {
			val = it.next();
			if (!out.containsKey(key))
				out.put(key, val);
		}
		it = in.iterator();
		while (it.hasNext()) {
			val = it.next();
			if (!out.containsKey(key))
				out.put(key, val);
		}
 	}
}
Comment 1 Olivier Thomann CLA 2011-08-19 22:13:42 EDT
Move to JDT/UI
Comment 2 Deepak Azad CLA 2011-10-18 22:23:41 EDT
The location is wrong because the value of variable 'val' changes in between, which is bug 27740.

*** This bug has been marked as a duplicate of bug 27740 ***