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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.106.7