官术网_书友最值得收藏!

Code check – part 2

One of our programmers, Pavni, tried using var with generics and collection classes, but her code doesn't seem to output the sorted collection of pens. Can you help? Check out the following code:

class Pen implements Comparable<Pen> {   
    String name;   
    double price;   
    public Pen(String name, double price) {   
        this.name = name;   
        this.price = price;   
    }   
    public int compareTo(Pen pen) {   
        return ((int)(this.price - pen.price));   
    }   
    public String toString() {   
        return name;   
    }   
   
    public static void main(String   args[]) {   
        var pen1 = new Pen("Lateral",   219.9);   
        var pen2 = new Pen("Pinker",   19.9);   
        var pen3 = new Pen("Simplie",   159.9);   
   
        var penList = List.of(pen1, pen2,   pen3);   
   
        Collections.sort(penList);   
        for (var a : penList)    
            System.out.println(a);   
    }   
}   

The answer to the code check: The issue here is trying to modify the immutable collection by using Collections.sort(). This is to emphasize that not all issues are related to the use of var.

主站蜘蛛池模板: 鹿泉市| 色达县| 阿图什市| 化德县| 鸡西市| 连城县| 玉溪市| 林州市| 镇坪县| 东乡| 大冶市| 东台市| 房山区| 合阳县| 肃宁县| 黄骅市| 行唐县| 汝阳县| 武定县| 浙江省| 连城县| 大埔县| 孟津县| 盐边县| 洛宁县| 马边| 璧山县| 淳安县| 新营市| 田阳县| 石景山区| 莱阳市| 西昌市| 龙海市| 崇仁县| 克什克腾旗| 丰都县| 威海市| 泌阳县| 大名县| 清流县|