2 回答
TA贡献1866条经验 获得超5个赞
是的,它将与countStatesCountByInitial. 主要区别在于每次找到匹配项时,您都希望将状态添加到数组中。由于我们事先不知道数组的大小,因此我们可能想使用 aList代替。
public State[] getStatesCountByInitial(char initial) {
ArrayList<State> found = new ArrayList<>();
// this is the same as before
for(int i = 0; i < states.length; i++) {
String testString = states[i].getName();
char[] stringToCharArray = testString.toCharArray();
for (char output : stringToCharArray) {
if(initial == output) {
// except here when you find a match, you add it into the list
found.add(states[i]);
}
}
}
// return as array
return found.toArray(new State[found.size()]);
}
正如帕特里克所建议的,我们可以List通过使用countStatesCountByInitial来初始化状态的大小来避免使用。
public State[] getStatesCountByInitial(char initial) {
int matchSize = countStatesCountByInitial(initial);
States[] found = new States[matchSize];
int foundIndex = 0;
// this is the same as before
for(int i = 0; i < states.length; i++) {
String testString = states[i].getName();
char[] stringToCharArray = testString.toCharArray();
for (char output : stringToCharArray) {
if(initial == output) {
// except here when you find a match, you add it into the array
found[foundIndex] = states[i];
foundIndex++;
}
}
}
// return the array
return found;
}
TA贡献1797条经验 获得超6个赞
您可以通过一种方法简单地完成这两种操作。
public static ArrayList<State> getStatesCountByInitial(char initial) {
ArrayList selectedStates = new ArrayList<State>();
for(int i = 0; i < states.length; i++) {
if(states.charAt(0) == initial){
selectedStates.add(states[i]);
}
}
return selectedStates;
}
此方法将返回一个数组列表。如果要获取计数,则调用此方法并获取数组的大小。
ArrayList<State> statesNew = getStatesCountByInitial('A');
int count = statesNew.size();
添加回答
举报