If I start with a method like this:
package com.sandbox;
import java.util.ArrayList;
import java.util.List;
public class Sandbox {
public static void main(String[] args) {
List<String> strings = new ArrayList<String>();
strings.add("a");
strings.add("b");
for (String string : strings) {
System.out.println(string);
}
}
}
If I highlight the first add(...) line and then extract method, the code turns into this:
package com.sandbox;
import java.util.ArrayList;
import java.util.List;
public class Sandbox {
public static void main(String[] args) {
List<String> strings = new ArrayList<String>();
addA(strings);
strings.add("b");
for (String string : strings) {
System.out.println(string);
}
}
private static void addA(List<String> strings) {
strings.add("a");
}
}
I almost never want this. I’d rather it do something like this:
package com.sandbox;
import java.util.ArrayList;
import java.util.List;
public class Sandbox {
public static void main(String[] args) {
List<String> strings = new ArrayList<String>();
strings.addAll(addA());
strings.add("b");
for (String string : strings) {
System.out.println(string);
}
}
private static List<String> addA() {
List<String> strings = new ArrayList<String>();
strings.add("a");
return strings;
}
}
Or maybe something like this:
package com.sandbox;
import java.util.ArrayList;
import java.util.List;
public class Sandbox {
public static void main(String[] args) {
List<String> strings = addA();
strings.add("b");
for (String string : strings) {
System.out.println(string);
}
}
private static List<String> addA() {
List<String> strings = new ArrayList<String>();
strings.add("a");
return strings;
}
}
Is there a way to make intellij extract methods this way?
You could get the second result by selecting the first two lines of the method (including the new ArrayList call).