有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (5) 个答案

  1. # 2 楼答案

    我经常使用强制转换来处理没有考虑泛型的库,或者当我需要向下转换某些对象以访问我知道是由子类实现的功能时,而不是由我正在使用的类实现的功能时。使用if (foo instanceof Bar)检查可能是明智的 但是,在做出那个决定之前

  2. # 3 楼答案

    当我们反序列化一个对象(例如从一个字符串)时,我们需要将该对象强制转换到类中,以便我们可以使用它的方法

  3. # 4 楼答案

    在Java中,无法声明泛型类型T的数组。例如,使用new T[10]声明数组是无效的:

    public class List<T> {
        T[] backing_array = new T[10]; // this line is invalid,
    
    
        public T Item(int index) {
            return backing_array[index]; // and therefore this line is invalid as well.
        }
    
        //etc...
    

    我们拥有的最佳替代解决方案是:

    public class List<T> {
        Object[] backing_array = new Object[10];
    
        public T Item(int index) {
            return (T) backing_array[index]; // notice that a cast is needed here if we want the return type of this function to be T
        }
    
        //etc...
    

    如果Java中不存在显式类型转换,就不可能构建泛型数组列表,因为不允许声明泛型类型为T的数组

  4. # 5 楼答案

    这里有一些

    要反转自动加宽,请执行以下操作:

    byte blammy = (byte)(schmarr & 0xF7);
    

    遗留代码:

    public void oldSchoolMethod(List oldSchoolListOfStrings)
    {
        String firstValue = (String)oldSchoolListOfStrings.get(0);
    }
    

    HTTP代码:

    public String getSchmarr(HttpServletRequest request)
    {
        HttpSession session = request.getSession();
        return (String)session.getAttribute("Schmarr");
    }
    

    编辑:“类型增加”更正为“类型加宽”