Using int as a type parameter for java.util.Dictionary

后端 未结 6 2132
孤独总比滥情好
孤独总比滥情好 2021-02-06 22:51

When I try to declare a Dictionary as such:

private Dictionary map;

The compiler gives me the following error:

相关标签:
6条回答
  • 2021-02-06 23:13

    To expand on TofuBeer's answer.

    int is a primitive

    Integer is an Object.

    Generics does not support primitives.

    0 讨论(0)
  • 2021-02-06 23:16

    In Java primitives aren't objects, so you can't use them in place of objects. However Java will automatically box/unbox primitives (aka autoboxing) into objects so you can do things like:

    List<Integer> intList = new LinkedList<Integer>();
    intList.add(1);
    intList.add(new Integer(2));
    ...
    Integer first = intList.get(0);
    int second = intList.get(1);
    

    But this is really just the compiler automatically converting types for you.

    0 讨论(0)
  • 2021-02-06 23:20

    In .Net, "primitive" types are backed by objects. In Java, there's a hard distinction between primitive types and Objects. Java 5 introduced autoboxing, which can coerce between the two in certain situations. However, because the Java generics system uses type-erasure, there isn't enough information to autobox in this case.

    0 讨论(0)
  • 2021-02-06 23:29

    Java collections only allow references not primitives. You need to use the wrapper classes (in this case java.lang.Integer) to do what you are after:

    private Dictionary<String, Integer> map;
    

    they you can do things like:

    int foo = map.get("hello");
    

    and

    map.put("world", 42);
    

    and Java uses autoboxing/unboxing to deal with the details of the conversion for you.

    Here is a little description on it.

    0 讨论(0)
  • 2021-02-06 23:29
    @XmlJavaTypeAdapter(value=MyAdapter.class, type=int.class)
    

    Thats the trick specify type to make it work with primitives

    In your adapter

    using the same in package-info will mean you do it globally for that package

    Found this after experimenting.

    public class MyAdapter extends XmlAdapter<String, Integer> {
    
    0 讨论(0)
  • 2021-02-06 23:34

    Because in Java the primitives are truely primitives. In Java int will pass by value, while Integer will pass a reference. In .NET int or Int32 etc. are just different names.

    0 讨论(0)
提交回复
热议问题