2014-09-29 3 views
2

과제가있어서 붙어 있습니다. 할당은이 메소드의 제네릭 클래스를 작성하는 것입니다.Java 일반 클래스와 갇혀 있습니다.

public static void main(String[] args) { 
    ValueStore<Object> myStore1 = new ValueStore<Object>(); 
    myStore1.set("Test"); 
    myStore1.get(); 

    /// 
    ValueStore<Object> myStore2 = new ValueStore<Object>(); 
    myStore2.set(myStore1); 
    myStore1 = myStore2.get(); 
} 

여기까지 왔습니다.

public class ValueStore<T> { 
    private T x; 

    public void set(T x) { 
     System.out.println(x); 
    } 

    public T get() { 
     return x; 
    } 
} 

mystore.set "test"는 인쇄 할 수 있지만 myStore2.set는 인쇄 할 수 없습니다. 그리고 왜 선생님이 참고 변수를 인수로 전달했는지 이해할 수 없습니다. 그렇게하면 콘솔에 ValueStore @ 15db9742가 표시됩니다. 아니면 그게 포인트 야?

왜 사람이 myStore2.set(myStore1); myStore1 = myStore2.get()이라고 말하는 이유와 그 뒤에 인쇄해야 할 논리를 설명 할 수 있습니까?

미리 감사드립니다. 그리고 내 텍스트가 모두 엉망이라면 미안 해요. 처음 여기.

+0

를) {}'방법 :

public static void main(String[] args) { // Type your store with String, which is what generics is about. ValueStore<String> myStore1 = new ValueStore<String>(); // Store a string in it. myStore1.set("Test"); // Get the object, and the typesystem will tell you it's a string so you can print it. System.out.println(myStore1.get()); /// ValueStore<Object> myStore2 = new ValueStore<Object>(); // Store your store. myStore2.set(myStore1); // The type system only knows this will return an Object class, as defined above. // So you cast it (because you know better). myStore1 = (ValueStore<String>) myStore2.get(); System.out.println(myStore1.get()); } public class ValueStore<T> { private T x; public void set(T x) { this.x = x; } public T get() { return x; } } 

이 코드는 다음을 인쇄 당신의'ValueStore' 클래스에서. – OldCurmudgeon

+5

확실히 'ValueStore # set'의 구현은'this.x = x;'를 포함해야한다고 생각하십니까? –

답변

2

나는 당신이 실제로 객체를 저장할 것이다 그래야 현재 방금

public void set(T x) { 
    System.out.println(x); 
    this.x = x; 
} 

같이 당신의 set() 방법에서 선을 누락 생각합니다.

0

설명 할 내용이 조금 더 있습니다. 요점은 ValueStore (이 예에서는 String)에 유형을 지정할 수 있다는 것입니다. 이렇게하면 타입 시스템에서 valuestoreget()을 호출하면 string이 반환된다는 것을 인식합니다. 이것은 사실 제네릭의 전체 요점입니다. object을 단순히 입력하면 get 메소드가 String을 리턴하므로 캐스트해야합니다 (두 번째 예와 같이). 선생님이 원하지만 당신은`문자열 toString을 (구현하여`ValueStore @ 15db9742` 문제를 해결 얻을 수있는 너무 명확하지

test 
test 
+0

매우 잘 설명되고 잘 쓰여졌습니다. 고마워요! – Kharbora

관련 문제