import java.util.*;
public class test { }
public static void main(String[] args) {
String str = "str";
int integer = 1;
HashMap map = new HashMap();
map.put("str",str);
map.put("integer",integer);
HashMap map1 = start(map);
System.out.println( map1.get("integer").getClass());
System.out.println(map);
} public static HashMap <String, String> start(HashMap hashmap) {
return hashmap;
} }
为什么打印出来的结果
是class java.lang.Integer
{integer=1, str=str}按照我想的应该结果是 String阿因为返回的是一个HashMap <String, String> 这种类型的阿
可是为什么还是class java.lang.Integer第二个问题啊很多方法把一个类名就是classname当作参数这是为什么啊?
跟传对象有什么不一样呢?
一个新new的classname
根传一个classname有什么区别阿?
谢谢阿
public class test { }
public static void main(String[] args) {
String str = "str";
int integer = 1;
HashMap map = new HashMap();
map.put("str",str);
map.put("integer",integer);
HashMap map1 = start(map);
System.out.println( map1.get("integer").getClass());
System.out.println(map);
} public static HashMap <String, String> start(HashMap hashmap) {
return hashmap;
} }
为什么打印出来的结果
是class java.lang.Integer
{integer=1, str=str}按照我想的应该结果是 String阿因为返回的是一个HashMap <String, String> 这种类型的阿
可是为什么还是class java.lang.Integer第二个问题啊很多方法把一个类名就是classname当作参数这是为什么啊?
跟传对象有什么不一样呢?
一个新new的classname
根传一个classname有什么区别阿?
谢谢阿
public class test { }
public static void main(String[] args) {
String str = "str";
int integer = 1;
HashMap map = new HashMap();
map.put("str",str);
map.put("integer",integer);
HashMap map1 = start(map);
System.out.println( map1.get("integer").getClass());
System.out.println(map);
} public static HashMap <String, String> load(HashMap<String,String> hashmap) {
return hashmap;
} }
而且这样写编译的时候也不抱错阿
实际上,你只是调用了Integer中的toString()方法,并不是调用了intValue()
如果想显示出int值,修改JDK中的Integer类里的toString()方法
一般JAVA类里都会含有toString()方法,他就是为了你如果要把类对象进行String输出时,调用的方法
泛型是Java在编译期完成的功能,它只是对后续的代码加上限制,实际上它并不会对已有内容进行判断所以你get(integer)回来的仍然是原来Integer值(put(int)编译器会将它变成put(Integer))后续代码加上限制?能具体点吗?
要求传递类名只是为了减少不必要的新建对象而已,如果那个方法只需要知道是一个什么样的类,那么如果要求对象则增加了外部调用程序的不必要新建过程如果一个方法的参数是对象和参数是类名那么调用的时候耗费的资源是不一样的?
ArrayList<String> list = ...
String a = list.get(0);
实际上会被编译器解释为:
ArrayList list = ...
String a = (String) list.get(0);所以它们在运行中是没有任何区别的。当然也不可能做到帮你转换list内部成员类型。
2、在调用这个方法的时候当然没有消耗上的区别,但是如果这个方法根本不需要这个类的实例
例如 Logger log = Logger.getInstance(MyClass.class);实际上getInstance()只是需要这个类的名称而已,根本不需要访问这个类的任何成员或变量
这样如果是传递对象,则白白浪费了新建对象的资源与时间