日期:2014-05-20  浏览次数:20642 次

java类型转换的问题
import java.util.HashMap;
import java.util.StringTokenizer;

public class HashMapSample {
HashMap<String, String[]> dict;
public HashMapSample() {
dict = new HashMap<String, String[]>();
}
public void putIntoDict( String key, String info ) {
StringTokenizer st = new StringTokenizer(info, "\n");
int length = st.countTokens();
String [] result = new String[length];
for (int i = 0; i < length; i++) {
result[i] = st.nextToken();
}

dict.put( key, result );
}
public void printWord( Object key ) {
    System.out.println( key + ":" );
    for( int j = 0; j < ( (String [])(dict.get(key)).length ); j++ ) {//这一行类型转换有错误,求助高手帮助。
                System.out.println( ((String [])dict.get(key))[j] );
    }
}
public void printDict() {
    Object [] keys = dict.keySet().toArray();
    for( int i = 0; i < keys.length; i++ ) {
     printWord( keys[i] );
    }
}
public static void main(String[] args) {
HashMapSample map = new HashMapSample();

String str = "adj : appearing earlier in the same text; \"flaws in the above interpretation\"\n" +
"adv 1: at an earlier place; \"see above\"\n"+
"2: in or to a place that is higher";

map.putIntoDict( "above", str );
map.printDict();
return;
}
}

------解决方案--------------------
楼主既然使用了泛型,没必要再强转了.

        for( int j = 0; j < dict.get(key).length ; j++ ) ////这一行类型转换有错误,求助高手帮助。dict.get(key)本身就是String[].不需要强转了。
        {
                System.out.println(dict.get(key)[j] );
        }

------解决方案--------------------
引用:
楼主既然使用了泛型,没必要再强转了.


Java code
?



12345

        for( int j = 0; j < dict.get(key).length ; j++ )    ////这一行类型转换有错误,求助高手帮助。dict.get(key)本身就是String[].不需要强转了。            {                 Sy……


正解!
使用了泛型 不用再转型
------解决方案--------------------
4楼正解,dict.get(key)就是一个数组类型不用转型了。
------解决方案--------------------
引用: