所以我昨天在一个测验中被要求为字符串数组的大小制作我自己的方法。我被告知我不能使用.length快捷方式。这是我的尝试,是吗?
//doesn't receive array! because it's a datamember in the class already
public int sizeOfArray(){
int counter = 0;
while(arrayName != empty){
arrayName[counter];
counter ++;
}
return counter;
}
答案 0 :(得分:4)
是不是?
没有。它甚至没有编译。最基本的想法是尝试挑起ArrayIndexOutOfBoundsException.
答案 1 :(得分:1)
嗯,这是一个满足要求的廉价解决方案(更不用说在恒定时间内运行):
Arrays.asList(arrayName).size()
请参阅:Arrays.asList()
请注意,如果它是一个基元数组(int
,double
,...),这将无法按预期工作。在这种情况下,它总是返回1
。由于我们专门处理String[]
,我们没有这样的问题。