0023 | Collections Framework

Tuesday, June 24th, 2008 Posted in Java | No Comments »

ไม่มีอะไรครับ เอา code มาเก็บไว้เฉยๆ 555
กลับมาอ่านอีกทีคงลืมแล้วแหงๆ ว่ามันไว้ทำอะไร

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.*;
class Product implements Comparable<Product>
{
public int id;
public String name;
public int qty;
public double price;
 
public Product(int id, String name, int qty, double price) {
this.id = id;
this.name = name;
this.qty = qty;
this.price = price;
}
 
public String toString() {
return this.id +:+ this.name +:+ this.qty +:+ this.price;
}
 
public int compareTo(Product s) {
return s.qty - this.qty;
}
}

———————————–

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.util.*;
class ProductDB
{
public static void main(String[] args)
{
List<Product> db = new LinkedList<Product>();
db.add(new Product(1, “pen”, 20, 5.50d));
db.add(new Product(2, “ruler”, 18, 10.00d));
db.add(new Product(3, “notebook”, 15, 18.50d));
db.add(new Product(4, “rubber”, 40, 15.00d));
db.add(new Product(5, “pencil”, 25, 3.00d));
Collections.sort(db);
for (Product i : db) {
System.out.println(i);
}
}
}

Tags: , ,