Answer the question
In order to leave comments, you need to log in
Removing data from an array, what's the catch?
I am writing a site in spring, but I can not remove data from the array, my code is:
Controller:
@RestController
public class IpController {
@Autowired
private IpService ipService;
@DeleteMapping("/ip/{id}")
public void deleteIp(@PathVariable Integer id) {
ipService.deleteIp(id);
}
@Service
public class IpService {
private List<Ip> ipList = new ArrayList<>(Arrays.asList(
new Ip(0,3002235620L,true,false,Timestamp.valueOf("2007-12-23 09:01:06")),
new Ip(1,3232235620L,false,true, Timestamp.valueOf("2016-12-23 09:01:06")),
new Ip(2,4294967295L,true,false, Timestamp.valueOf("2017-10-08 17:24:06")),
new Ip(3,3294967295L,true,false, Timestamp.valueOf("2017-11-08 17:24:06"))
));
public void deleteIp(Integer id) {
//ipList.remove(id);
ipList.removeIf(i -> i.getId().equals(id)); // РАБОТАЕТ !!!!
}
// В дальнейшем все это дело будет работать с БД
Answer the question
In order to leave comments, you need to log in
Look: List has 2 remove methods:
boolean remove(Object o);
E remove(int index);
The first deletes by object. Roughly speaking, it searches the list for the passed object, and if it finds it, it deletes it.
The second deletes by index - that is, deletes the object with index index.
Pay attention to the parameter type: the first is Object, the second is a scalar int.
In ipList.remove(id) you pass a variable of type Integer (which, in turn, is inherited from Object). So java calls the first method. He tries to find this object in the list, but it is not there - you have Ip there, and, as a result, does not delete anything.
You need to cast your Integer to int (using id.intValue() or (int) id). Then java will call the second method, which removes by index.
But! Most likely, in the request you will not pass the index, but the id of the Ip class. So, in fact, the solution with ipList.removeIf(i -> i.getId().equals(id)); is the most correct. Well, or use Map, as mentioned above.
Apparently, you are trying to remove data from an array by an identifier (assigned by you).
So, - here (and everywhere in arrays in java) two (or any number) is an index, i.e. the number of the record to be deleted.
Again, if I understand correctly what you want to achieve, then you need to use map, not array. ipList.remove(2);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question