- 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.
推薦閱讀
- 微信公眾平臺(tái)與小程序開發(fā):從零搭建整套系統(tǒng)
- Android和PHP開發(fā)最佳實(shí)踐(第2版)
- 深入實(shí)踐Spring Boot
- AIRAndroid應(yīng)用開發(fā)實(shí)戰(zhàn)
- 組態(tài)軟件技術(shù)與應(yīng)用
- 領(lǐng)域驅(qū)動(dòng)設(shè)計(jì):軟件核心復(fù)雜性應(yīng)對(duì)之道(修訂版)
- Linux C編程:一站式學(xué)習(xí)
- Python機(jī)器學(xué)習(xí):預(yù)測(cè)分析核心算法
- 零基礎(chǔ)學(xué)HTML+CSS第2版
- Python大規(guī)模機(jī)器學(xué)習(xí)
- C語(yǔ)言從入門到精通
- HTML5與CSS3權(quán)威指南
- Java EE實(shí)用教程
- Visual C#(學(xué)習(xí)筆記)
- PHP高性能開發(fā):基礎(chǔ)、框架與項(xiàng)目實(shí)戰(zhàn)