Integer转换为String类型


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

  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;
    }
    
}

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM