Java几个简单例子

来源:互联网 发布:希特勒侄女知乎 编辑:程序博客网 时间:2024/06/01 10:37

例子1

Class.isPrimitive()方法:判断Class类是否是基础数据类型

Class.isAssignableFrom:用来判断一个类Class1和另一个类Class2是否相同或是另一个类的子类或接口,

      isAssignableFrom的参数类型都是Class 

      instanceof 的参数类型是对象

@Testpublic void testAssignableFrom() {Assert.assertEquals(true, boolean.class.isPrimitive());Assert.assertEquals(false, Boolean.class.isPrimitive());Assert.assertEquals(true, Object.class.isAssignableFrom(String.class));Assert.assertEquals(true, Object.class.isAssignableFrom(Boolean.class));Assert.assertEquals(false, Object.class.isAssignableFrom(boolean.class));}

例子2

WeakReference:表示弱引用,当执行gc时。会回收对象。

SoftReference:表示强引用,执行gc时并不会回收,只有当内存吃紧时,才会回收,适全Cache操作

/** * WeakReference 是弱引用,当执行gc时。会垃圾回收,适合debug,内存监控 */    public void testWeakReference() {    A a = new A();    a.str = "Hello weakrefrence";    WeakReference<A> weak = new WeakReference<A>(a);    a = null;    int i = 0;    while (weak.get() != null) {    System.out.println(String.format("Get str from object of weakReference : %s, count: %d", weak.get().str, ++i));    if (i % 10 == 0) {    System.gc();    System.out.println("System.gc() was invoked!");    }    try {     Thread.sleep(500); } catch (Exception e) {// TODO: handle exception}    }    System.out.println("object a was cleared by JVM");    }/** * SoftReference是强引用,gc并不会回收,只有当内存吃紧时才会被回收,适合Cache * 以下程序会一直跑。除非内存不够用 */@Test    public void testSoftReference() {    A a = new A();    a.str = "Hello softReference";    SoftReference<A> soft = new SoftReference<A>(a);    a = null;    int i = 0;    while (soft.get() != null) {    System.out.println(String.format("Get str from object of softReference : %s, count: %d", soft.get().str, ++i));    if (i % 10 == 0) {    System.gc();    System.out.println("System.gc() was invoked!");    }    try {     Thread.sleep(500); } catch (Exception e) {// TODO: handle exception}    }    System.out.println("object a was cleared by JVM");    }

例子3

System.identityHashCode():对象内存地址来计算哈希值,返回默认的hashCode,不管子类是否重写的hashCode方法

hashCode:Object的方法。

public class TestIdentityHashCode {@Testpublic void testIdentityHashCode() {String a = "a";TestA b = new TestA();TestB c = new TestB();Assert.assertEquals(false, a.hashCode() == System.identityHashCode(a));Assert.assertEquals(true, b.hashCode() == System.identityHashCode(b));Assert.assertEquals(false, c.hashCode() == System.identityHashCode(c));}}class TestA {}class TestB {@Overridepublic int hashCode() {return 11110;}}


0 0
原创粉丝点击