首页 > 其他 > 详细

Integer转换为String类型

时间:2017-06-24 16:05:17      阅读:294      评论:0      收藏:0      [点我收藏+]

在学习泛型时,遇到了一个小问题:

  Integer i = 2;
  String s = (String) i;

  Integer类型转换为String类型,本来想直接用强制转换,结果报错:

  Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

  经过搜索资料后发现,这样的转换只能通过以下方式进行:

   Integer i = 2;
  String s = i.toString();    

  这里给出一个稍微复杂点的代码,这个例子是Oracle官方解释泛型与不使用泛型的优势的一个例子,关于泛型的更具体的解释我可能会在之后的某个时间重新写一篇。

package graph;

import java.util.*;

public class JustTest {	
	public static void main (String[] args) {
		ObjectContainer myObj = new ObjectContainer();
		//store a string
		myObj.setObj("Test");
		System.out.println("Value of myObj:" + myObj.getObj());
		//store an int (which is autoboxed to an Integer object)
		myObj.setObj(3);
		System.out.println("Value of myObj:" + myObj.getObj());
		
		List objectList = new ArrayList(); // 不指定类型时,默认使用原始类型 Object
		objectList.add(myObj);
		//We have to cast and must cast the correct type to avoid ClassCastException!
		//String myStr = (String)((ObjectContainer)objectList.get(0)).getObj(); // 运行时这里报错
		String myStr = ((ObjectContainer)objectList.get(0)).getObj().toString();
		System.out.println(myStr);
	}
}


class ObjectContainer {
    private Object obj;

    public Object getObj() {
        return obj;
    }

    public void setObj(Object obj) {
        this.obj = obj;
    }
    
}

  

Integer转换为String类型

原文:http://www.cnblogs.com/satchel/p/7073517.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!