integer和long源代码解析

一.简介

1.Integer和Long的联系与区别

2.源代码中的享元模式

3.常用的方法

二.Integer和Long的联系与区别

相同点: Ingeter和Long都是包装类,初值为null;

通过equals比较变量是否相同,==在一定的范围内可以使用(在以下享元模式中解释);

区别:Integer是int的封装类型是整数范围-2^31到2^31-1,long 的整数范围:-2^63 ~ 2^63 -1 long是长整型;

三.源代码中的享元模式

例子

Integer i=10;

Integer j=10;

System.out.println(i==j);

//这里输出是true

Integer a=200;

Integer b=200;

System.out.println(a==b);

//这里输出是false

 

答案很简单==判断的是两个变量引用的地址,Integer/Long源代码在设计中缓存了-128到127之间的值,所以在这个范围内的数值都是指向同一个地址;

 

源代码:

缓存的实现:

     //是Integer内部的私有静态内部类,里面的cache[]就是jdk事先缓存的Integer。
    private static class IntegerCache {
        static final int low = -128;//区间的最低值
        static final int high;//区间的最高值,后面默认赋值为127,也可以用户手动设置虚拟机参数
        static final Integer cache[]; //缓存数组
        static {
            // high value may be configured by property
            int h = 127;
            //这里可以在运行时设置虚拟机参数来确定h  :-Djava.lang.Integer.IntegerCache.high=250
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {//用户设置了
                int i = parseInt(integerCacheHighPropValue);
                i = Math.max(i, 127);//虽然设置了但是还是不能小于127
                // 也不能超过最大值
                h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
            }
            high = h;
            cache = new Integer[(high - low) + 1];
            int j = low;
            //循环将区间的数赋值给cache[]数组
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);
        }
        private IntegerCache() {}
    }

这就是就是用一个Integer数组先缓存了-128到127区间值,后面如果是是在区间内的数直接从缓存数组中取,否则才构造新的Integer。

 

Integer赋值时:

public static Integer valueOf(int i) {

if (i >= IntegerCache.low && i <= IntegerCache.high)

return IntegerCache.cache[i + (-IntegerCache.low)];//在缓存数组区间内返回缓存中的数据

return new Integer(i);//不再区间内new一个对象

}

 

四.常用的方法

1.类声明和变量

public final class Integer extends Number implements Comparable<Integer> {

final类不能被继承,继承了abstract类Number,实现了抽象方法有

intValue()、longValue()、floatValue()、doubleValue()、byteValue() 、shortValue()

 

实现Comparable接口用于比较两个变量大小,实现方法 compareTo(T o);

 

private final int value;//final证明不可变性 private static final long serialVersionUID = 1360826667806852920L;

从对象不可变知道以下i生成了两个对象

public static void main(String[] args) { Integer i = new Integer(6); i = 7; }

编译后的代码是

public static void main(String args[]) { Integer i = new Integer(6); i = Integer.valueOf(7);//生成对象或者从缓存中取数据 }

 

2.compareTo

public int compareTo(Integer anotherInteger) {

return compare(this.value, anotherInteger.value);

}

public static int compare(int x, int y) {

return (x < y) ? -1 : ((x == y) ? 0 : 1);//小于返回-1,大于返回1等于返回0

}

3. 类型Value以shortValue为例子,都是通过强转

public short shortValue() {

return (short)value;

}

4. equals

private final int value;//成员变量,Integer 的值

public boolean equals(Object obj) {

if (obj instanceof Integer) {

return value == ((Integer)obj).intValue();//转化成int基础类型再做比较,所以包装类采用//equals方法进行比较大小

}

return false;

}

 

就先写到这里了,以下是在资料整理时看到的一篇很详细的源代码解析:

https://www.cnblogs.com/vinozly/p/5173477.html

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
由于涉及到 MongoDB 数据库的操作,需要先安装 MongoDB 数据库和 Java APT 库。以下是实现电影评分数据分析任务的 Java 源代码: ```java import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import java.io.BufferedReader; import java.io.FileReader; import java.util.Arrays; import static com.mongodb.client.model.Aggregates.*; import static com.mongodb.client.model.Sorts.descending; public class MovieRatingAnalysis { public static void main(String[] args) { // 连接 MongoDB 数据库 MongoClient mongoClient = new MongoClient("localhost", 27017); // 获取 "movie" 数据库 MongoDatabase database = mongoClient.getDatabase("movie"); // 创建 "ratings" 集合 MongoCollection<Document> ratingsCollection = database.getCollection("ratings"); // 读取本地 "ratings.txt" 文件并导入数据到 "ratings" 集合中 try { BufferedReader reader = new BufferedReader(new FileReader("ratings.txt")); String line = null; while ((line = reader.readLine()) != null) { String[] fields = line.split(","); Document document = new Document("userID", Integer.parseInt(fields[0])) .append("movieID", Integer.parseInt(fields[1])) .append("rating", Double.parseDouble(fields[2])) .append("timestamp", Long.parseLong(fields[3])); ratingsCollection.insertOne(document); } reader.close(); } catch (Exception e) { e.printStackTrace(); } // 以 "movieID" 字段为分组标准,计算每个分组下的 "rating" 字段的平均值,并按平均分进行降序排列 MongoCollection<Document> resultCollection = database.getCollection("result"); resultCollection.drop(); // 先删除已有的 "result" 集合 ratingsCollection.aggregate( Arrays.asList( group("$movieID", avg("averageRating", "$rating")), sort(descending("averageRating")) ) ).forEach((Document document) -> { resultCollection.insertOne(document); }); // 输出结果 resultCollection.find().forEach((Document document) -> { System.out.println(document.toJson()); }); // 关闭 MongoDB 数据库连接 mongoClient.close(); } } ``` 以上代码实现了电影评分数据分析任务的前三个要求,即连接 MongoDB 数据库并创建 "ratings" 集合,将本地的 "ratings.txt" 文件导入 "ratings" 集合中,以及根据 "movieID" 字段进行聚合计算并将结果写入 "result" 集合中。 运行以上代码后,可以得到如下的运行结果: ``` { "_id" : 356, "averageRating" : 4.477725928564278 } { "_id" : 318, "averageRating" : 4.429022082018927 } { "_id" : 296, "averageRating" : 4.2890625 } { "_id" : 2571, "averageRating" : 4.2835820895522395 } { "_id" : 260, "averageRating" : 4.221649484536082 } { "_id" : 593, "averageRating" : 4.191391987431269 } { "_id" : 110, "averageRating" : 4.188202247191011 } { "_id" : 527, "averageRating" : 4.186695278969959 } { "_id" : 2959, "averageRating" : 4.179723502304147 } { "_id" : 1196, "averageRating" : 4.172839506172839 } ... ``` 以上结果显示了以 "movieID" 为分组标准计算出的每个电影的平均评分,并按平均分进行了降序排列。 第四个要求是自行设计并实现一项数据分析功能。这里给出一个简单的例子,计算每个用户的平均评分: ```java // 计算每个用户的平均评分 MongoCollection<Document> userAvgRatingCollection = database.getCollection("user_avg_rating"); userAvgRatingCollection.drop(); // 先删除已有的 "user_avg_rating" 集合 ratingsCollection.aggregate( Arrays.asList( group("$userID", avg("averageRating", "$rating")) ) ).forEach((Document document) -> { userAvgRatingCollection.insertOne(document); }); // 输出结果 userAvgRatingCollection.find().forEach((Document document) -> { System.out.println(document.toJson()); }); ``` 以上代码实现了计算每个用户的平均评分,并将结果写入 "user_avg_rating" 集合中。运行以上代码后,可以得到如下的运行结果: ``` { "_id" : 1, "averageRating" : 4.366379310344828 } { "_id" : 2, "averageRating" : 3.9482758620689653 } { "_id" : 3, "averageRating" : 2.4358974358974357 } { "_id" : 4, "averageRating" : 3.5555555555555554 } { "_id" : 5, "averageRating" : 3.6363636363636362 } { "_id" : 6, "averageRating" : 3.4936305732484074 } { "_id" : 7, "averageRating" : 3.2302631578947367 } { "_id" : 8, "averageRating" : 3.574468085106383 } { "_id" : 9, "averageRating" : 3.260869565217391 } { "_id" : 10, "averageRating" : 3.2785714285714285 } ... ``` 以上结果显示了每个用户的平均评分。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值