- Java 11 and 12:New Features
- Mala Gupta
- 149字
- 2021-07-02 12:27:00
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.
推薦閱讀
- Data Visualization with D3 4.x Cookbook(Second Edition)
- Python編程自學(xué)手冊(cè)
- The Modern C++ Challenge
- 控糖控脂健康餐
- iOS開發(fā)實(shí)戰(zhàn):從零基礎(chǔ)到App Store上架
- JSP開發(fā)案例教程
- Mastering Apache Spark 2.x(Second Edition)
- Visual C#.NET程序設(shè)計(jì)
- Python High Performance Programming
- C語(yǔ)言程序設(shè)計(jì)與應(yīng)用(第2版)
- Apache Solr PHP Integration
- Mastering VMware Horizon 7(Second Edition)
- Building UIs with Wijmo
- 像程序員一樣使用MySQL
- Implementing DevOps with Ansible 2