카테고리 없음
[자바] 이 배열의 크기를 아는 방법
필살기쓰세요
2021. 1. 24. 20:29
먼저 배열이 가득 찰 때까지 add를 호출 한 다음 제거하고 배열이 비워 질 때까지 제거한 횟수를 계산하면 다음과 같은 크기가됩니다.
SomeArray a = ...
SomeThingThatArrayCanStore something = ...;
while (!a.full()) {
a.add(something);
}
int size = 0;
while (!a.empty()) {
a.remove()
size++;
}
// here you have the size
-------------------당신은 필요하지 않습니다 full
: 그것은 빨간 청어입니다.
다음은 임시 컨테이너를 명시 적으로 만들지 않고이를 달성하는 솔루션입니다. 기본적으로 스택 프레임을 사용하여 제거 된 요소의 컨테이너를 만듭니다.
이 A
배열의 유형이고 a
인스턴스이고 remove()
함수가 제거 된 객체를 반환하면
int size(int n, A a){
if (a.empty()){
return n; // all done, n holds the number of elements removed
}
Object o = a.remove(); // pop the element
int ret = size(n + 1, a); // call self with the array truncated
a.add(o); // push the element back
return ret;
}
처음 n
에 0 으로 설정하여 호출하면 한 가지 방법 입니다. 스택 프레임을 만드는 데는 엄청난 비용이 들지만 이상한 우아함이 있습니다.
리플렉션과 함께 재미있는 것을 시도해보세요. 리플렉션을 사용하면 비공개 필드와 알 수없는 필드에 액세스 할 수 있습니다. 그것은 어둠의 마법과 같습니다 : 강력하지만 위험합니다!
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.List;
public class ArrayFinder {
public void printAllArraysLength(A a) throws IllegalArgumentException, IllegalAccessException {
for (Field field : A.class.getDeclaredFields()) { // get all private fields
field.setAccessible(true); // private are now public !
Object array = field.get(a); // get the field content.
try{
System.out.println(field.getName() + " length : " + getArrayLenth(array));
}catch(Exception e){
System.out.println(field.getName() + " is not an array");
}
}
}
private int getArrayLenth(Object array) {
Class arrayClass = array.getClass().getComponentType();
if(arrayClass == null){
// no component type, maybe a list.
return ((List) array).size();
}
else {
if (arrayClass.isPrimitive()) {
return Array.getLength(array);
}else{
return ((Object[]) array).length;
}
}
}
}
좋습니다. 교사가 추가 / 제거 / 비우기 및 전체 작업을 수행하기를 기대하는 것은 아닐 수 있습니다.
출처
https://stackoverflow.com/questions/39917203