2011-07-04 2 views
2

어떤 이유로이 문제가 발생합니다.특정 개체를 Java의 특정 배열에 캐스트

두 개의 Java Object가 있는데, 둘 다 원시 또는 비 기본 배열을 포함하여 무엇이든 될 수 있습니다.

평등 검사를 수행해야합니다.

배열 인 경우 런타임 인스턴스 대신 내용을 확인해야합니다.

그래서 예를 들어, 나는 다음과 같은 방법이 있다고 가정 해 봅시다 :

/** 
    * Returns true if the two parameters are arrays, and they both contain 
    * the same content. 
    * @param aObject1 An object 
    * @param aObject2 An object 
    * @return 
    */ 
    private boolean equalsArray(Object aObject1, Object aObject2) { 
     if(aObject1==null){ 
     return false; 
     } 
     if(aObject2==null){ 
     return false; 
     } 
     if(!aObject1.getClass().isArray()){ 
     return false; 
     } 
     if(!aObject2.getClass().isArray()){ 
     return false; 
     } 
     //How do I check if the two arrays here contain the same objects 
     //without knowledge of their type??? 

    } 

참고 배열은 아무것도 할 수있는, 그리고 가장 가능성 [] 객체되지 않습니다, 오히려 푸 [] 또는 바 [ ].

제안 사항? 객체 []에 캐스트 할 수 없기 때문에 Array.equals (Object [], Object [])를 수행 할 수 없습니다. 당신이해야합니다 그러나

+1

'를 Arrays.equals (([]) aObject1는, (개체 []) aObject2이 객체)'는 물론 캐스트의 수에'Object' 갈 수있는 방법입니다 'Object []'. – anubhava

+0

@anubhava parms가 프리미티브 (primitive) 배열 인 경우 Object []에 캐스트가 실패합니다. – pholser

+0

@ Tovi7 내 대답을 확인하십시오 –

답변

2

사용 java.lang의 :-) 수동으로 작성하지 않으려는 물론 어느 - 멋진가있다

+0

+1 : 이것은 가장 단순합니다. 'int []'와'Integer [] '가 같을 수 있음을 의미합니다. –

+1

또는 다차원 배열을 올바르게 처리해야하는 경우 항목 동일성을 테스트 할 때 재귀 적으로 메서드를 호출하십시오. 또는 앞서 언급 한 Commons Lang 메서드를 사용하십시오. – pholser

0

당신은 방법이 없기 때문에 내용에 대한 등호를 구현하는

Arrays.equals(Object[] a, Object[] a2) 

을 사용할 수 있습니다 : 당신이 구현하는 경우

o1.equals(o2) 

이 해당 객체에 대해 동일 작동합니다. 비 기본 유형의

모든 원시 유형에 대한

Arrays.equals 

재정있다. 당신이

public static boolean isEquals(Object array1, Object array2) { 
    return new EqualsBuilder().append(array1, array2).isEquals(); 
} 

public EqualsBuilder append(Object lhs, Object rhs) { 
    if (isEquals == false) { 
     return this; 
    } 
    if (lhs == rhs) { 
     return this; 
    } 
    if (lhs == null || rhs == null) { 
     this.setEquals(false); 
     return this; 
    } 
    Class lhsClass = lhs.getClass(); 
    if (!lhsClass.isArray()) { 
     // The simple case, not an array, just test the element 
     isEquals = lhs.equals(rhs); 
    } else if (lhs.getClass() != rhs.getClass()) { 
     // Here when we compare different dimensions, for example: a boolean[][] to a boolean[] 
     this.setEquals(false); 
    } 
    // 'Switch' on type of array, to dispatch to the correct handler 
    // This handles multi dimensional arrays of the same depth 
    else if (lhs instanceof long[]) { 
     append((long[]) lhs, (long[]) rhs); 
    } else if (lhs instanceof int[]) { 
     append((int[]) lhs, (int[]) rhs); 
    } else if (lhs instanceof short[]) { 
     append((short[]) lhs, (short[]) rhs); 
    } else if (lhs instanceof char[]) { 
     append((char[]) lhs, (char[]) rhs); 
    } else if (lhs instanceof byte[]) { 
     append((byte[]) lhs, (byte[]) rhs); 
    } else if (lhs instanceof double[]) { 
     append((double[]) lhs, (double[]) rhs); 
    } else if (lhs instanceof float[]) { 
     append((float[]) lhs, (float[]) rhs); 
    } else if (lhs instanceof boolean[]) { 
     append((boolean[]) lhs, (boolean[]) rhs); 
    } else { 
     // Not an array of primitives 
     append((Object[]) lhs, (Object[]) rhs); 
    } 
    return this; 
} 
1

는 다음과 같이 실행이

boolean org.apache.commons.lang.ArrayUtils.isEquals(Object array1, Object array2) 

에서 유틸리티를 동일 .reflect.Array : 배열이 중첩 된 배열을 가질 수있는 경우

if (Array.getLength(first) != Array.getLength(second)) 
     return false; 

    for (int i = 0; i < Array.getLength(first); ++i) { 
     Object firstItem = Array.get(first, i); 
     Object secondItem = Array.get(second, i); 
     if (!(firstItem == null ? secondItem == null : firstItem.equals(secondItem))) 
      return false; 
    } 
    return true; 
0

당신은 Arrays.equal(..)를 사용하거나 수 Arrays.deepEquals(..)

+0

아니요. Foo [] 클래스가있는 경우 Foo [] to Object []가 될 수 없으므로 예외가 발생합니다. – Tovi7

+0

@ Tovi7 : 사용자 의견을 이해할 수 없습니다. 'Foo []'는 Object입니다. []': 캐스팅 할 필요 없음 – MarcoS

+0

런타임에 "Foo []"인 컴파일 시간 "Object"가 있습니다. Object []에 캐스트해야합니다. 그렇지 않으면 작동하지 않습니다.Object []로 캐스팅하고 메소드를 실행하면 (예 : 원래 질문에서 말했듯이) 메소드에서 classcastexceptions가 발생합니다. – Tovi7

0

에 대해 어떻게 :

if(aObject1.getClass().getName().equals(aObject2.getClass().getName())) 
return Arrays.equals(aObject1, aObject2); 
else return false; 
관련 문제