2012-12-08 3 views
1

이 첫 번째 부분은 웹에서 찾은 예제이며 다른 솔루션을 빠르게 시도하도록 수정되었습니다. 제목이 나올 때 WordHold 객체를 가져 오는 방법을 알아낼 수 없으므로 WordHold 객체를 검색해야 할 때 수정할 수 있습니다.HashTable Java에서 개체를 가져 오려고 시도합니다.

import java.util.Collection; 
import java.util.Enumeration; 
import java.util.Hashtable; 
import java.util.Set; 

public class HashtableDemo { 

    public static void main(String args[]) { 
     WordHold temp = new WordHold("test1", "test2"); 
     WordHold temp2; 
     // Creating Hashtable for example 
     Hashtable companies = new Hashtable(); 

     // Java Hashtable example to put object into Hashtable 
     // put(key, value) is used to insert object into map 
     companies.put("Google", temp); 
     companies.put("Nokia", "Finland"); 
     companies.put("Sony", "Japan"); 

     // Java Hashtable example to get Object from Hashtable 
     // get(key) method is used to retrieve Objects from Hashtable 
     temp2 = companies.get("Google"); 

     // Hashtable containsKey Example 
     // Use containsKey(Object) method to check if an Object exits as key in 
     // hashtable 
     System.out.println("Does hashtable contains Google as key: " 
      + companies.containsKey("Google")); 

     // Hashtable containsValue Example 
     // just like containsKey(), containsValue returns true if hashtable 
     // contains specified object as value 
     System.out.println("Does hashtable contains Japan as value: " 
      + companies.containsValue("Japan")); 

     // Hashtable enumeration Example 
     // hashtabl.elements() return enumeration of all hashtable values 
     Enumeration enumeration = companies.elements(); 

     while (enumeration.hasMoreElements()) { 
      System.out 
      .println("hashtable values: " + enumeration.nextElement()); 
     } 

     // How to check if Hashtable is empty in Java 
     // use isEmpty method of hashtable to check emptiness of hashtable in 
     // Java 
     System.out.println("Is companies hashtable empty: " 
      + companies.isEmpty()); 

     // How to find size of Hashtable in Java 
     // use hashtable.size() method to find size of hashtable in Java 
     System.out.println("Size of hashtable in Java: " + companies.size()); 

     // How to get all values form hashtable in Java 
     // you can use keySet() method to get a Set of all the keys of hashtable 
     // in Java 
     Set hashtableKeys = companies.keySet(); 

     // you can also get enumeration of all keys by using method keys() 
     Enumeration hashtableKeysEnum = companies.keys(); 

     // How to get all keys from hashtable in Java 
     // There are two ways to get all values form hashtalbe first by using 
     // Enumeration and second getting values ad Collection 

     Enumeration hashtableValuesEnum = companies.elements(); 

     Collection hashtableValues = companies.values(); 

     // Hashtable clear example 
     // by using clear() we can reuse an existing hashtable, it clears all 
     // mappings. 
     companies.clear(); 
    } 
} 

하위 클래스가 사용됩니다.

public class WordHold 
{ 
    // instance variables - replace the example below with your own 
    private String wrongWord; 
    private String correctWord; 

    private WordHold next; 

    public WordHold(String wordWrong, String wordCorrect) 
    { 
     wrongWord = wordWrong; 
     correctWord = wordCorrect; 
    } 

    /** 
    * Returns the wrong word 
    * 
    * @return  The stored wrong word. 
    */ 
    public String getWrongWord() 
    { 
     return wrongWord; 
    } 

    /** 
    * Returns the correct word 
    * 
    * @return  The stored wrong word. 
    */ 
    public String getCorrectWord() 
    { 
     return correctWord; 
    } 

    /** 
    * Returns the next element 
    * 
    * @return  The next element in list. 
    */ 
    public WordHold getNext() 
    { 
     return next; 
    } 

    /** 
    * Sets next element in the list. 
    */ 
    public WordHold setNext() 
    { 
     return next; 
    } 

    public String toString() 
    { 
     String temp = (wrongWord + " no " + correctWord); 

     return temp; 
    } 
} 
+0

그것은 나에게 보이는 당신의 wordwrong 클래스의 문자열) 모두에 대해 게터, 당신이 겪고있는 문제가 무엇을 만들? – Austin

+0

코드가 컴파일되지 않습니다. 당신이하려는 것은 무엇입니까? –

+0

당신의 subClass가 불필요 할 수 있다고 생각합니다. (이것은 partital 구현 일 수 있습니다). 난 당신이 해시 테이블에 해시 테이블을 넣을 수 있다는 것을 알고 있었는지 궁금했다. –

답변

1

을 컴파일하지 말아야 해시 회사

temp2 = companies.get("Google");에서 검색됩니다 난 단지 당신의 코드를 통해 미끄러 져 당신이 제네릭을 사용하지 않는 것을 발견하여 컬렉션. WorldHold 객체를 Hashtable에서 가져 오려고하면 GenerHeics를 사용하지 않는 것처럼 WorldHold에 캐스팅해야합니다. java.lang.Object을 반환합니다.

처럼 해시 테이블 선언 :

Hashtable<WordHold> companies = new Hashtable<WordHold>(); 

이 문제를 해결할 것입니다.

제네릭을 사용하지 않으려면 반환 된 개체를 WordHold로 명시 적으로 캐스팅해야합니다.

temp2 = (WordHold)companies.get("Google"); 

나는 강하게 당신 자바 1.5를 사용하는 경우가 제네릭를 사용하는 것이 좋습니다. 컬렉션에 컴파일 타임 안전을 추가하기 때문입니다. 그 (것)들을 사용하지 않는 경우에, 당신은 당신의 수집으로 단순히 어떤 목표든지 추가 할 수 있고, 또한 당신은 수집에서 물체를 다시 retriving하고있는 동안 그 같은 원하지 않는 던지기를 제거 할 수있다. 당신이 (it.next()를 에서 System.out.println 말 클래스 간단한에서 끌어하려는 경우

Read about generics In java

+0

당신은 매우 고맙습니다. 다른 사람들이 입력 한 것과 약간의 차이점은 첫 번째 예제처럼 해시 테이블을 선언하는 것입니다 : 'Hashtable <(키 유형), WordHold> 회사 = 새 Hashtable <(키 유형), WordHold >(); ' – Inerg

+0

@Inerg 컴파일 시간 안전을 추가하고 원치 않는 모든 캐스트를 제거 할 수 있기 때문에 제네릭 사용을 제안했습니다. 만약 당신이 해시 테이블에 대해 generics를 사용했다면, 콜렉션에서 객체를 다시 얻는 동안 wordhod로 다시 캐스팅 할 필요가 없습니다.:) – PermGenError

+1

당신이 제네릭의 제안에 맞았는데, 내가 사용하기를 좋아하는 것입니다. API에서 개체를 만들 때 제가 할 수있는 것을 보지 못했습니다. 내 실수는 간단한 것이지만 그것을 알게 해주셔서 대단히 감사합니다. – Inerg

1

WordHold t = (WordHold)companies.get("Google");

이 줄은

0

희망이 예는 U에게

import java.util.*; 

public class hashtable { 

     public static void main(String[] args) { 
       Hashtable hastab = new Hashtable(); 
       hastab.put("a", "andrews"); 
       hastab.put("b", "bob"); 
       hastab.put("c", "christina"); 
       hastab.put("d", "dude"); 
       hastab.put("e", "era"); 
       Set s = hastab.entrySet(); 
       Iterator it = s.iterator(); 

       while (it.hasNext()) { 
         System.out.println(it.next()); 
       } 
     } 
} 

을하는 데 도움이됩니다. 값을(). getWordWrong를())

(당신이`get`를 호출하는 것처럼

관련 문제