2014-10-01 5 views
-1
import java.util.*; 

public class MyClass<Item> implements Iterable<Item> { 
    public Iterator<Item> iterator(){ return new ListIterator();} 

    public class ListIterator implements Iterator<Item>{ 
     ... 
    } 

    public static void main(String[] args){ 

    } 
} 

이 반복기를 제네릭 타입으로 어떻게 사용할 수 있습니까? 에서 non-static class Item cannot be referenced from a static context커스텀 클래스의 제네릭 타입에 대한 반복자 사용

MyClass deq = new MyClass(); 
ListIterator it = deq.iterator(); 

결과 : non-static class Deque2.ListIterator cannot be referenced from a static context

에서 non-static class Item cannot be referenced from a static context

MyClass deq = new MyClass(); 
ListIterator<Item> it = deq.iterator(); 

결과에

MyClass <Item> deq = new MyClass(); 
ListIterator<Item> it = deq.iterator(); 

결과 : 이들은 내 '주'기능에 시도한 방법이다

편집 :

메소드 대신 클래스를 호출했습니다. 작동 방식 :

Iterator it = deq.iterator();

iterator()에서 반환 된 인스턴스의 유형이 ListIterator 였으므로 그 유형이 'it' 인 것으로 선언해야한다고 생각했습니다.

+0

여기에 대한 답변입니다 : http://stackoverflow.com/questions/10301907/why-do-i-get-non-static-variable-this-cannot-be-referenceced-from-a-static-contex – tiguchi

+0

왜냐하면 아래로 투표 했니? 나는 나의 문제를 분명히 열거하고 정확히 내가 겪고있는 오류를 보여 주었다. 이런. –

+0

스택 오버플로에 공통적 인 오류는 아니지만 내부 클래스는 일반 'Item' 유형 매개 변수를 사용합니다. –

답변

3

당신은 당신의 클래스 선언에서

public class MyClass<Item> implements Iterable<Item> { 

, 당신은 새로운 유형의 변수, Item를 정의를 선언했습니다. 이 유형 변수는 인스턴스 (또는 인스턴스 참조 값으로 해석되는 표현식)에 바인드됩니다.

정적 컨텍스트에 인스턴스가 없기 때문에 정적 컨텍스트에서는 사용할 수 없습니다.

ListIterator은 내부 클래스입니다. 타입 변수와 같은 문제가 있습니다. 작동하려면 인스턴스가 필요합니다.

관련 문제