Does not remove items from cart. When I hit "delete" the items are still there. Only performs the total price calculation. Cart isn't repository , instead Fiction item is a repositry entity , saved in the database Thanks for your help This is my code :
@Component
public class Cart {
private List <Fiction> fictions = new ArrayList<Fiction> ();
private float totale = 0.0f;
public Cart() {
super();
}
public void add(Fiction fiction) {
fictions.add(fiction);
this.totale = totale + fiction.getPrezzo();
}
public void remove(Fiction fiction) {
Iterator<Fiction> iterator = fictions.iterator();
while(iterator.hasNext()) {
Fiction item = iterator.next();
if(item.equals(fiction)) {
iterator.remove();
}
} this.totale = totale - fiction.getPrezzo();
}
controller
Does not remove items from cart.
When I hit "delete" the items are still there.
Only performs the total price calculation.
Thanks for your help
This is my code :
@Controller
public class CartController {
@Autowired
Cart carrello;
@Autowired
private FictionRepo fictionRepo;
@RequestMapping("/deleteToCart/{id}")
public String deleteToCart(@PathVariable("id") Long id ) {
Fiction fictions = fictionRepo.findById(id).orElseThrow(() -> new IllegalArgumentException("Fiction non trovata"));
System.out.println(" sto per cancellare");
carrello.remove(fictions);
System.out.println(" ho cancellato");
return "redirect:/indexCart";
}
}
Override the equals
to get your code working. Refer the following example:
// Overriding equals() to compare two Fiction objects
@Override
public boolean equals(Object o) {
// If the object is compared with itself then return true
if (o == this) {
return true;
}
/* Check if o is an instance of Fiction or not
"null instanceof [type]" also returns false */
if (!(o instanceof Fiction)) {
return false;
}
// typecast o to Fiction so that we can compare data members
Fiction c = (Fiction) o;
// Compare the data members and return accordingly
return this.id.equals(c.getId());
}