回答編集履歴

2

Orderクラスの無駄を省く

2016/11/23 15:19

投稿

swordone
swordone

スコア20651

test CHANGED
@@ -5,3 +5,85 @@
5
5
 
6
6
 
7
7
  ここからは構成上の話になりますが、FoodクラスとOrderクラスというのは不自然です。「食べ物」を意味するクラスFoodがあり、そのFoodが「注文されたもの」か「在庫にあるもの」かという色づけがされるわけです。
8
+
9
+
10
+
11
+ 率直に考えればこうなります。
12
+
13
+ ```java
14
+
15
+ class Food{
16
+
17
+ public int id;
18
+
19
+ public String name;
20
+
21
+ public Food(int id,String name){
22
+
23
+ this.id = id;
24
+
25
+ this.name = name;
26
+
27
+ }
28
+
29
+
30
+
31
+ public boolean equals(Object o) {
32
+
33
+ if (o == this) return true;
34
+
35
+ if (o.getClass() != this.getClass()) return false;
36
+
37
+ Food f = (Food)o;
38
+
39
+ return this.id == f.id && this.name.equals(f.name);
40
+
41
+ }
42
+
43
+ //hashcodeの実装は省略
44
+
45
+ }
46
+
47
+
48
+
49
+ public class App {
50
+
51
+ public static void main(String[] args) {
52
+
53
+
54
+
55
+ List<Food> orderList = new ArrayList<>();
56
+
57
+ List<Food> foodList = new ArrayList<>();
58
+
59
+
60
+
61
+ orderList.add(new Food(1,"アップル"));
62
+
63
+ orderList.add(new Food(2, "バナナ"));
64
+
65
+ orderList.add(new Food(3, "綿菓子"));
66
+
67
+
68
+
69
+ foodList.add(new Food(1,"アップル"));
70
+
71
+ foodList.add(new Food(2, "バナナ"));
72
+
73
+
74
+
75
+ for (int i = 0; i < orderList.size(); i++) {
76
+
77
+ if(!foodList.contains(orderList.get(i))){
78
+
79
+ System.out.println(orderList.get(i));
80
+
81
+ }
82
+
83
+
84
+
85
+ }
86
+
87
+ }
88
+
89
+ ```

1

2種類のくらさ

2016/11/23 15:19

投稿

swordone
swordone

スコア20651

test CHANGED
@@ -1,3 +1,7 @@
1
1
  containsの判定にはequalsを使います。デフォルトでは「同じオブジェクト」の時だけtrueとなるので、現状等しいオブジェクトを見つけられません。
2
2
 
3
3
  equalsをオーバーライドして、等しいの定義付けをする必要があります。
4
+
5
+
6
+
7
+ ここからは構成上の話になりますが、FoodクラスとOrderクラスというのは不自然です。「食べ物」を意味するクラスFoodがあり、そのFoodが「注文されたもの」か「在庫にあるもの」かという色づけがされるわけです。