[英]How to find out the length of an array without .length
我必须找出一个字符数组有多长。 我不能使用 .length 因为它是不允许的。 你能帮我么??? 错误:运算符 != 未定义参数类型 char, null
我有这样的...
public void len(){
int i=0;
while(i>0){
if (Array[i] != null) {
System.out.println("not null");
}
else{
System.out.println(i);
}
}
}
不允许使用.length
字段来访问数组的长度甚至没有任何意义。 我想你一定是误会了什么。
无论如何,这是获取长度的“肮脏”方法:
public static <T> int lengthOfArray(T[] array) {
int count = 0;
while (true) {
try {
T t = array[count];
} catch (ArrayIndexOutOfBoundsException e) {
return count;
}
count++;
}
}
请注意,您需要使用Character[]
而不是char[]
。
请不要在生产代码中使用它!
这只是另一种方法,它是使用List
接口然后从那里获取数据的一个小技巧,我不知道它是否允许并且肯定不是最好的方法。
public static <T> int len(T[] array) {
return Arrays.asList(array).size();
}
请记住,您不能将原始类型数组传递给此函数。
顺便说一句,你的程序实际上什么都不做,因为 i 永远不会优于 0,你去吧,这是最简单的方法:
public void len(){
end = false;
for(int i = 0; !end; i++){
try{
char c = Array [i];
System.out.println("not null : " + i);
}
catch (ArrayIndexOutOfBoundsException){
System.out.println("End of the array");
end = true;
}
}
}
int length = java.lang.reflect.Array.getLength(array);
访问不存在的数组元素不会计算为 null,它会引发异常,因此您无法将其与 null 进行比较。 这是一个通过测试异常来找到长度并使用二分搜索最小化测试次数的解决方案:
static int getArrayLengthStupidWay(Object array) {
int low = 0, high = Integer.MAX_VALUE;
while (low != high) {
int mid = (low + high) >>> 1;
try {
java.lang.reflect.Array.get(array, mid);
low = mid + 1;
} catch (ArrayIndexOutOfBoundsException ex) {
high = mid;
}
}
return low;
}
什么是字符链?
int lenght = new String(charArray).size();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.