[英]Making own java method for array length issue
因此,昨天有人在測驗中要求我為字符串數組的大小制作自己的方法。 有人告訴我我不能使用.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;
}
這樣對嗎?
不。它甚至不編譯。 基本思想是嘗試引發ArrayIndexOutOfBoundsException.
好吧,這是一個滿足要求的
廉價
解決方案(更不用說在恆定時間內運行):
Arrays.asList(arrayName).size()
請參閱: Arrays.asList()
請注意,如果它是原始數組( int
, double
,...),則無法按預期工作。 在這種情況下,它將始終返回1
。 由於我們專門處理String[]
,因此不會出現此類問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.