如果你堅持保持的String [],你可以委託 「髒活」,以現有的API方法,即Arrays.copyOfRange(Object[] src, int from, int to)
短的,獨立的,正確的(可編譯),例如:
import java.util.Arrays;
public class R {
public static String[] trimEmployees(String[] employees, int maxSize) {
return Arrays.copyOfRange(employees, 0, maxSize);
}
public static void main(String[] args) {
String[] employees = new String[] { "Jennifer", "Paul", "Tori",
"Zulema", "Donald", "Aleshia", "Melisa", "Angelika", "Elda",
"Elenor", "Kimber", "Eusebia", "Mike", "Karyn", "Marinda",
"Titus", "Miki", "Alise", "Liane", "Suzanne", "Dorothy" };
int max = 20;
System.out.println(String.format("Input employees (len=%d): %s ",
employees.length, Arrays.toString(employees)));
if (employees.length > max) {
employees = trimEmployees(employees, max);
System.out.println(String.format("Trimmed employees (len=%d): %s",
employees.length, Arrays.toString(employees)));
}
}
}
打印:
Input employees (len=21): [Jennifer, Paul, Tori, Zulema, Donald, Aleshia, Melisa, Angelika, Elda, Elenor, Kimber, Eusebia, Mike, Karyn, Marinda, Titus, Miki, Alise, Liane, Suzanne, Dorothy]
Trimmed employees (len=20): [Jennifer, Paul, Tori, Zulema, Donald, Aleshia, Melisa, Angelika, Elda, Elenor, Kimber, Eusebia, Mike, Karyn, Marinda, Titus, Miki, Alise, Liane, Suzanne]