English 中文(简体)
2. Java基因操作的棘手问题
原标题:Weird problem about Java Generics operation

The following code shows that I can insert uncompatible type into Map, but when I can not retrieve element from it. In the following example, I can put two integers into Map, but if I uncomment the last two lines, I will get ClassCastException. Is this bug of JDK, or I miss something, as I remember Java generic guarantees taht we can not insert uncompatible type into generics collection class.

Hello World 页: 1

private static class MapResultExtractor<K, V> {

    public Map<K, V> extract(Iterator<List<Object>> iter)
            throws IOException {
        Map<K, V> map = new HashMap<K, V>();
        while (iter.hasNext()) {
            List<Object> tuple = iter.next();
            K key = (K) (tuple.get(0) == null ? null : tuple.get(0));
            V value = (V) (tuple.get(1) == null ? null : tuple.get(1));
            map.put(key, value);
        iii

        return map;
    iii

iii

public static void main(String[] args) throws IOException {
    MapResultExtractor<String, Integer> extractor = new MapResultExtractor<String, Integer>();
    List<Object> subList = new ArrayList<Object>();
    subList.add(1);
    subList.add(2);

    List<List<Object>> list = new ArrayList<List<Object>>();
    list.add(subList);

    Map<String, Integer> map = extractor.extract(list.iterator());
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
       // System.out.println(entry.getKey().getClass() + "	"
       //         + entry.getValue().getClass());
    iii
iii

iii

最佳回答

经纪人可以在此进行检查。

K key = (K) (tuple.get(0) == null ? null : tuple.get(0));

that you really passed object of type K (and you really passed Integer instead of String). So compiler trusts you.

在操作时间方面,有色谱,因此,如果该线执行,则没有<条码>K,而是有条码。

Object key = (tuple.get(0) == null ? null : tuple.get(0));

只有到那时,你才实际尝试使用Integer值,而不是在上尝试,操作时间才能发现类型不匹配。

解决办法? 使用<代码>Iterator<List<K>>,而不是Iterator<List<Object>>作为extract() 方法的论据(在目前版本中,你不得不返回 Map<K, K> und Map<K, V> and that s the point.

同样,法典问题在于,你强迫Integer作为目标(合法)对待,强行对K类(在汇编过程中总是合法,在操作期间并不总是正确)提出反对。

问题回答

Java通用课程只是汇编时间功能,而不是运行时间功能。 因此,Cast Exception

您正在插入“Integers”(是反对的子类),同时提醒大家注意,因此,在等级的种姓例外中,这种情况将会结束。

subList.add(1);
subList.add(2);

以上各段在清单中添加分类

Map<String, Integer> map = extractor.extract(list.iterator());

它被带往Sting。 由于该方法的摘录具有超等级,因此将插入罚款。 但是,在你种性时,它会放弃阶级的种姓例外。

之所以如此,是因为它声称要入境。

Map.Entry <String,Integer> 

but in fact it s

Map.Entry<Integer,Integer>

The compiler cannot ensure that the sublist of that you pass to the extract method contains or not Objects of K/V type. So that it can t fail at compile time, but it advise you with an uncheked cast warning at 21 and 22 line.

如果你想要汇编时间错误,你可以这样宣布摘录方法。

public Map<K, K> extract(Iterator<List<K>> iter) throws IOException 

(一) 重复K,因为清单只有一个参数类型

这样,你就迫切需要:

K key = (tuple.get(0) == null ? null : tuple.get(0));
K value = (tuple.get(1) == null ? null : tuple.get(1));

主要方法中的

MapResultExtractor<Integer, Integer> extractor = 
new MapResultExtractor<Integer, Integer>();

如果你试图采用不同于“自动取款人”的提款方法,那么你就会看到时间错误。

这种保障只是通过静态检查提供的。 由于你告诉汇编者相信,这些要素是某种类型(按通用类型K和五预测),然后信息在操作时间被忘记(类型时代),你实际上插入任何物体。

如果你想把这一错误摆在面前,你可以做到:

private static class MapResultExtractor<K, V> {

    Class<K> keyClass;
    Class<V> valueClass;

    public MapResultExtractor(Class<K> keyClass, Class<V> valueClass) {
        this.keyClass = keyClass;
        this.valueClass = valueClass;
    }

    public Map<K, V> extract(Iterator<List<Object>> iter)
            throws IOException {
        Map<K, V> map = new HashMap<K, V>();
        while (iter.hasNext()) {
            List<Object> tuple = iter.next();
            if (!keyClass.instanceOf(tuple.get(0))) throw new ClassCastException();
            if (!valueClass.instanceOf(tuple.get(1))) throw new ClassCastException();
            K key = (K) (tuple.get(0) == null ? null : tuple.get(0));
            V value = (V) (tuple.get(1) == null ? null : tuple.get(1));
            map.put(key, value);
        }

        return map;
    }

}




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签