草庐IT

包装类

zh-Note 2023-04-16 原文

包装类

  1. 针对八种基本定义相应的引用类型——包装类
  2. 有类的特点,就可以调用类中的方法。
  • 包装类的分类

    基本数据类型 包装类
    boolean Boolean
    char Character
    byte Byte
    short Short
    int Integer
    long Long
    float Float
    double Double

  • 包装类和基本数据的转换(装箱和拆箱)

    1. jdk5 前的是手动装箱和拆箱的方式。(装箱:基本类型 -> 包装类,反之拆箱)
    2. jdk5 后(含jdk5) 的自动装箱和拆箱方式。
    3. 自动装箱底层调用的是valueOf方法,比如Integer.valueOf()。
    4. 其他包装类的用法类似。
    public class Integer01 {
        public static void main(String[] args) {
            // 演示Integer的装箱和拆箱
            // jdk5.0 前是手动装箱和拆箱
            //手动装箱 int -> Integer
            int n1 = 100;
            Integer integer = new Integer(n1);
            Integer integer1 = Integer.valueOf(n1);
    
            // 手动拆箱 Integer -> int
            int i = integer.intValue();
    
            //jdk5以后,就可以自动装箱和自动拆箱
            int n2 = 200;
            //自动装箱 int -> Integer
            Integer integer2 = n2;//在底层依旧使用的是Integer.valueOf(n2)方法,这个方法,只是优化了语法
            //自动拆箱 Integer -> int
            int n3 = integer2;//在底层依旧使用的是intValue()方法。
        }
    }
    
  • 包装类型和String类型的相互转换

    public class WrapperVSString {
        public static void main(String[] args) {
            //包装类 -> String
            Integer i = 100;//自动装箱
            //方式(1)
            String str = i + "";
            //方式(2)
            String str1 = i.toString();
            //方式(3)
            String str3 = String.valueOf(i);//底层用的还是toString方法
    
            //String -> 包装类(Integer)
            String str4 = "1234";
            //方式(1):
            Integer i2 = Integer.parseInt(str4);//有使用到自动装箱,以下两个方法实质都是利用者方式1
    
            //方式(2):
            Integer i1 = Integer.valueOf(str4);
            //Integer.valueOf(str4) 中 valueOf方法的源码:
            //public static Integer valueOf(String s) throws NumberFormatException {
            //        return Integer.valueOf(parseInt(s, 10));
            //    }
    
            //方式(3):
            Integer i3 = new Integer(str4);
            //new Integer(str4) 中 这个构造方法源码:
            //public Integer(String s) throws NumberFormatException {
            //        this.value = parseInt(s, 10);
            //    }
        }
    }
    
  • Integer创建机制

    Integer类内部有一个静态内部类IntegerCache,内部有静态成员储存了-128到127的Integer数组。

    当利用valueOf方法创建Integer类对象时,而值又在[-128,127]范围内时它就会返回这个数组中值对应的对象。

    //IntegerCache源码    
    private static class IntegerCache {
            static final int low = -128;
            static final int high;
            static final Integer cache[];
    
            static {
                // high value may be configured by property
                int h = 127;
                String integerCacheHighPropValue =
                    sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
                if (integerCacheHighPropValue != null) {
                    try {
                        int i = parseInt(integerCacheHighPropValue);
                        i = Math.max(i, 127);
                        // Maximum array size is Integer.MAX_VALUE
                        h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                    } catch( NumberFormatException nfe) {
                        // If the property cannot be parsed into an int, ignore it.
                    }
                }
                high = h;
    
                cache = new Integer[(high - low) + 1];
                int j = low;
                for(int k = 0; k < cache.length; k++)
                    cache[k] = new Integer(j++);
    
                // range [-128, 127] must be interned (JLS7 5.1.7)
                assert IntegerCache.high >= 127;
            }
    
            private IntegerCache() {}
        }
    
    //valueOf方法    
    public static Integer valueOf(int i) {
            if (i >= IntegerCache.low && i <= IntegerCache.high)
                return IntegerCache.cache[i + (-IntegerCache.low)];
            return new Integer(i);
        }
    

    预先就创建好了共256个Integer对象供后续使用。整个IntegerCache类中的代码均被static修饰,目的是确保在被实际使用时就已经完成了初始化,IntegerCache类中使用cache[]数组缓存了从-128~127供256个Integer对象。

    回到valueOf方法,可见,如果传入的int值在cache缓存-128~127的范围中,则直接返回预先创建好的对象,如果不在范围中,则创建一个新的Integer对象返回。

    //案例
    public void method1(){
    	Integer i new Integer(1);
    	Integer j new Integer(1);
    	System.out.printin(i==j)://False
    	//所以,这里主要是看范围-128~127就是直接返回
    	Integer m=1;//底层Integer.valueOf(1);->阅读源码
    	Integer n=1;//底层Integer.valueOf(1)i
    	System.out.printin(m == n); //T
    	//所以,这里主要是看范围-128~127就是直接返回
    	//,否则,就new Integer(xx);
    	Integer x = 128;//底层Integer.valueOf(1):
    	Integer y = 128;//底层Integer..valueOf(1):
    	System.out.printin(x == y)//False
    }
    

有关包装类的更多相关文章

  1. ruby-on-rails - Cucumber 是否只是 rspec 的包装器以帮助将测试组织成功能? - 2

    只是想确保我理解了事情。据我目前收集到的信息,Cucumber只是一个“包装器”,或者是一种通过将事物分类为功能和步骤来组织测试的好方法,其中实际的单元测试处于步骤阶段。它允许您根据事物的工作方式组织您的测试。对吗? 最佳答案 有点。它是一种组织测试的方式,但不仅如此。它的行为就像最初的Rails集成测试一样,但更易于使用。这里最大的好处是您的session在整个Scenario中保持透明。关于Cucumber的另一件事是您(应该)从使用您的代码的浏览器或客户端的角度进行测试。如果您愿意,您可以使用步骤来构建对象和设置状态,但通常您

  2. ruby-on-rails - Rails 通过 div 包装有错误的字段 - 2

    当验证未通过时,如何停止Rails更改我的代码。每次rails用包裹我的字段...我可以编辑fields_with_error类.fields_with_error{display:inline}这行得通,但它是hacky 最佳答案 没关系。使用CSS而不是这样做。ActionView::Base.field_error_proc=Proc.newdo|html_tag,instance_tag|"#{html_tag}"end我觉得这更hacky:) 关于ruby-on-rails-R

  3. ruby - memcached 是否有类似 ORM 的包装器 - 2

    我正在寻找一个ruby​​gem(或rails插件),它以与ActiveRecord抽象SQL细节相同的方式抽象出memcached的细节。我不是正在寻找有助于在memcached中缓存ActiveRecord模型的东西。我确信大约有4215个gem可以帮助解决这个问题。理想情况下,我希望能够执行以下操作:classApple然后能够做类似的事情:my_apple=Apple.find('somememcachedkey')这将在memcached中查找此类的JSON表示并将其反序列化。我也许还能做类似的事情:my_apple.color="red"#persistchangesbac

  4. ruby - 如何通过包含模块来包装 Ruby 方法的调用? - 2

    我想在我的某些类(class)中发生某些事情时收到通知。我想以这样一种方式进行设置,即我的方法在这些类中的实现不会改变。我在想我会有类似以下模块的东西:moduleNotificationsextendActiveSupport::ConcernmoduleClassMethodsdefnotify_when(method)puts"the#{method}methodwascalled!"#additionalsuitablenotificationcode#now,runthemethodindicatedbythe`method`argumentendendend然后我可以像这样

  5. ruby-on-rails - 如何在 Rails 助手中将内容包装在 html 中 - 2

    我想在Rails3助手中用HTML包装一些内容,这样在我看来我可以这样做:我有一个如下所示的辅助方法:defrounded_box(&block)str="str"rawstrend我现在使用它的方式返回正确包装在HTML字符串中的内容,但不会在呈现rounded_boxblock中的任何erb之前返回(例如,在这种情况下,target.text呈现两次,一次包装,一次不包装)。有更好的方法吗?为简单起见,我想避免使用content_tag,但如果这是我能做到的唯一/最佳方式。 最佳答案 在block上调用capture而不是yie

  6. sql - 将所有 Controller 操作包装在 Rails 中的事务中 - 2

    是否可以设置一个Rails应用程序,以便所有Controller操作都自动包装在一个事务中,并在出现未挽救的异常时自动回滚?我正在开发一个Rails3应用程序,目前正在执行一项相当棘手的操作,该操作会进行大量数据库更改。而且我一直弄错了很多次!一段时间后,我意识到我的代码无法正常工作,因为我最终在数据库中得到了不一致的数据。我可以很容易地用一个事务来包装它(这是一个明显需要的实例!)。然而,这让我想到,至少在开发过程中,将这个想法应用于每个Controller操作会很有用。假设这是可能的,这有什么缺点吗? 最佳答案 有关信息,我在我

  7. ruby - 为 API 包装器实现类似 ActiveRecord 的关联 - 2

    我最近写了ParseResource,它是Parse.com's的RubyAPI包装器REST接口(interface)。下面是一些基本用法:classPost"Helloworld",:author=>"Alan",:body=>"ipsolorem")这个项目还很年轻,我真正想要实现的一个功能是关联。像这样:classAuthor"Alan",:email=>"alan@example.com")p=Post.create(:title=>"Associated!",:body=>"ipsolorem",:author=>a)p.author.class#=>Authorp.aut

  8. ruby - 在 ruby​​ 中使用 PortAudio 包装器将声音录制到 .wav - 2

    我最近一直在研究ruby​​,我决定开始一个简单的项目来编写一个ruby​​脚本,将线路输入声音记录到.wav文件中。我发现ruby​​不能很好地访问硬件设备(它可能不应该),但是PortAudio可以,而且我发现了一个很棒的PA包装器here(它不是gem,我认为是因为它使用ruby​​的ffi附加到PortAudio,而且PA库可能在很多地方)。我一直在摸索PortAudio的文档和示例以了解PA的工作原理。我已经很多年没有写过或读过C了。我在创建过程中应该将哪些参数传递给流以及在创建过程中传递给缓冲区时遇到了困难。例如,frame到底是什么,它与channel和samplerat

  9. ruby-on-rails - Rails 3. simple_format 不要将结果包装在段落标签中 - 2

    如何使simple_format不将返回值包装在p标签中?simple_format"*" 最佳答案 您可以指定wrapper_tag选项。simple_format'Hello',{},wrapper_tag:'span'此代码将是:Hello 关于ruby-on-rails-Rails3.simple_format不要将结果包装在段落标签中,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/ques

  10. ruby-on-rails - 跳过与 simple_form 关联的包装器 - 2

    我正在使用simple_form,我想知道在处理关联选择时是否可以跳过任何包装div。谢谢 最佳答案 如果您使用类似f.association:product的东西,您可以像这样删除生成的标签和包装器:f.association:product,label:false,wrapper:false 关于ruby-on-rails-跳过与simple_form关联的包装器,我们在StackOverflow上找到一个类似的问题: https://stackoverf

随机推荐