forked from MoriMorou/Java2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBox.java
More file actions
58 lines (47 loc) · 1.73 KB
/
Copy pathBox.java
File metadata and controls
58 lines (47 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.util.ArrayList;
import java.util.List;
// Пустой объявленный класс, где Т обозначает тип, который будет заменен реальным типом.
public class Box<F extends Fruit>{
// Объявляем объекты лист и вес
private ArrayList<F> fruits;
private float totalWeight;
public Box() {
fruits = new ArrayList<>();
}
// В контруктор передаем ссылку на лист
public Box(ArrayList<F> fruits) {
this.fruits = fruits;
}
public Box(F fruit) {
fruits = new ArrayList<>();
fruits.add(fruit);
}
public ArrayList<F> getFruits() {
return fruits;
}
public void setFruits(ArrayList<F> fruits) {
this.fruits = fruits;
}
//The java.util.ArrayList.size() method returns the number of elements in this list i.e the size of the list.
//ArrayList get(int index) method is used for fetching an element from the list. We need to specify the index while
//calling get method and it returns the value present at the specified index.
public float getTotalWeight() {
if (fruits.size() != 0) {
int i = 0;
totalWeight = fruits.size() * fruits.get(i).getWeight();
} else {
System.out.println("We don't have fruits in a box. ");
}
return totalWeight;
}
public boolean compare(Box<?> otherBox) {
return getTotalWeight() == otherBox.getTotalWeight();
}
public void replaceAllFruitsToOtherBox(Box<F> otherBox) {
otherBox.fruits.addAll(fruits);
fruits.clear();
}
public void addFruit(F fruitToAdd) {
fruits.add(fruitToAdd);
}
}