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

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.

主站蜘蛛池模板: 宽城| 永春县| 阿勒泰市| 长汀县| 平谷区| 株洲市| 清水河县| 潮安县| 南昌市| 湄潭县| 安溪县| 云南省| 衡东县| 贵阳市| 连云港市| 申扎县| 盐城市| 浦北县| 泊头市| 浑源县| 浦县| 筠连县| 壶关县| 仪征市| 阿图什市| 蕲春县| 茶陵县| 栖霞市| 沂水县| 祁阳县| 伊春市| 山西省| 连南| 固原市| 葵青区| 秦安县| 英吉沙县| 柳江县| 溆浦县| 乡城县| 吉首市|