Bug 70922 Convert to Enhanced For [quick assist]
I implemented as a QuickAssist a convertion from old For loop to the EnhancedFor in Java 1.5 In order to activate it you should place the cursor over the for keyword and trigger the QuickAssist (Ctrl + 1). If the preconditions for this refactoring are satisfied, one would be offered to "Convert to Enhanced For". If you don't see this QuickAssist then it might be the case that some conditions for this refactoring could not be satisfied (e.g. the whole iteration over the collection is done sequentially, there is only Read Access to the collection, etc.). This is an example of conversion. Initially you have: int[] array= {1,2}; for (int i= 0, max= array.length; i < max; i++){ System.out.println(array[i]); } After applying the quick fix you get: int[] array= {1,2}; for (int element : array) { System.out.println(element); } Or here is a smarter one. Initially you have: String[] names= {"John","Mary"}; for (int i = 0; i < names.length; i++) { String name= names[i]; if (name != null) System.out.println(name); } After the quick fix you get: String[] names= {"John","Mary"}; for (String name : names) { if (name != null) System.out.println(name); } NOTE: currently (July 27th), I handle only the cases when one iterates over Arrays. In a future version one will be able to convert a For loop that iterates over a generic collection as well.
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickAssistProcessor.java
}
			int statementStart= statement.getStartPosition();
			int statementEnd= statementStart + statement.getLength();
			
			int offset= context.getSelectionOffset();
			int length= context.getSelectionLength();
			if (length == 0) {
				if (offset != statementEnd) { 
					return false;
				}
			} else {
				if (offset > statementStart || offset + length < statementEnd) { 
					return false;
				}
			}
			statement= (Statement) statement.getParent();
		}
		
		StructuralPropertyDescriptor childProperty= null;
		ASTNode child= null;
		switch (statement.getNodeType()) {
			case ASTNode.IF_STATEMENT:
				int selectionStart= context.getSelectionOffset();
				int selectionEnd= context.getSelectionOffset() + context.getSelectionLength();
				ASTNode then= ((IfStatement) statement).getThenStatement();
				if (selectionEnd <= then.getStartPosition() + then.getLength()) {
					if (!(then instanceof Block)) {
						childProperty= IfStatement.THEN_STATEMENT_PROPERTY;
						child= then;
					}