2016-06-29 5 views
1

오브젝트를 Java 형식으로 참조 할 수 있습니까?오브젝트 유형별로 참조 Java

private static class Pet { 
    private String name; 

    public String getName() { 
     return name; 
    } 

    public Pet setName(String name) { 
     this.name = name; 
     return this; 
    } 
} 

public static class CAT extends Pet{} 

public static class DOG extends Pet{} 

나는 애완 동물을 허용하는 연결리스트로 개와 고양이의 애완 동물의 무리를 넣어 :

예를 들어, 나는이 있습니다. 다음을 통해 마지막 색인 인 개를 찾고 싶습니다.

 private Pet dequeueDog() { 
     int locationDog = linkedList.lastIndexOf(DOG); 
     return linkedList.remove(locationDog); 
    } 

이렇게 할 수 있습니까? 객체의 유형을 기준으로 객체를 참조하려면?

+4

아니요 거꾸로 목록을 반복, 테스트 개체가 해당 유형의 참조의 경우 수 있습니다. –

+0

환상적입니다. 실제로 객체가 유형의 참조인지 테스트 할 수 있는지 물어 보려고했습니다. 답을 써서 이것을 해결할 수 있습니까? getclass() 사용. – lawonga

+1

@lawonga 또는 instanceof. – immibis

답변

1

자바 (8)을 사용하는 가정하면, 그 검색 한 후 마지막으로 개를 찾기 위해 비 DOG의를 filter 수 있습니다

private static Pet dequeueDog(LinkedList<Pet> linkedList) { 

    List<Pet> dogList = linkedList.stream().filter(u -> u.getClass() == DOG.class).collect(Collectors.toList()); 
    int locationDog = linkedList.lastIndexOf(dogList.get(dogList.size()-1)); 
    return linkedList.remove(locationDog); 
} 

Here의 나는 두 DOG의에 넣어 예 그리고 세 개의 CAT을 목록에 넣고 두 번째로 DOG을 넣습니다. 너는 dogList.get()에 넣는 것을 바꿈으로써 이것을 nth제거 할 수있다.

1

자바에서는 가능하지만 조금 못 생깁니다. 검색하려는 목록과 유형이 있으면이 방법을 사용합니다. 이 활용 제네릭으로 작동 http://pastebin.com/yX1v6L9p가 (명시 적 유형 매개 변수가 엄격하게 필요하지 않습니다.)

과를 확인하는 클래스의 방법 isAssignableFrom :

public static <T> T getLastOfType(List<? super T> list, Class<T> type) { 
    Object[] arr = list.toArray(); 
    for (int i = arr.length - 1; i >= 0; i--) { 
     if (arr[i] == null) continue; 

     if (type.isAssignableFrom(arr[i].getClass())) { 
      return (T) arr[i]; 
     } 
    } 
    return null; 
} 

그리고 여기에 행동에 그것의 작은 테스트입니다 원하는 유형에 대한 목록의 오브젝트 유형.

1

instanceof처럼 사용하십시오. List`이 그것을 할 수있는 기본 방법이없는`-하지만

package com.example; 

import static org.junit.Assert.*; 

import java.util.Arrays; 
import java.util.List; 

import org.junit.Test; 

public class ExampleTest { 

    class Pet { 
    } 

    class CAT extends Pet { 
    } 

    class DOG extends Pet { 
    } 

    private Pet dequeueDog(List<Pet> linkedList) { 
     int i = 0; 
     Integer foundIndex = null; 
     DOG found = null; 
     for (Pet pet : linkedList) { 
      if (pet instanceof DOG) { 
       foundIndex = i; 
       found = (DOG) pet; 
      } 
     } 
     if (foundIndex != null) { 
      linkedList.remove(foundIndex); 
     } 
     return found; 
    } 

    @Test 
    public void test() { 
     DOG someDog = new DOG(); 
     CAT someCat = new CAT(); 
     assertEquals(someDog, dequeueDog(Arrays.asList(someCat, someDog, null, someDog, someCat))); 
    } 

}