I had a project about LRU on Java. I used ArrayList to keep my Objects (which named Kisi), deleted the last Obj to set size of the ArrayList (to 5). I have finished but I wonder that is there any easier way to do this?
By the way I used swing and spring to create obj's.
There is a part of my code:
Kisi k = ctx.getBean("kisi", Kisi.class);
k.setName(textName.getText());
k.setSurname(textSurname.getText());
for (int i = 0; i < liste.size(); i++) {
// if (k.getName().equalsIgnoreCase(liste.get(i).getName())
// && k.getSurname().equalsIgnoreCase(liste.get(i).getSurname())) {
// liste.remove(i);
// }
if(k.equals(liste.get(i))) {
liste.remove(i);
}
}
liste.add(0, k);
model.clear();
if (liste.size() == 6) {
JOptionPane.showMessageDialog(contentPane, liste.get(liste.size()-1)+" Silindi");
liste.remove(liste.size()-1);
}
for (Kisi kisi : liste) {
model.addElement(kisi);
}
textName.setText("");
textSurname.setText("");
The loop you are using to find the index of k
object that matches your item in liste
ArrayList
could give better performance and readability if you use indexOf
method instead.
That is:-
Instead of the for loop;
for (int i = 0; i < liste.size(); i++) {
// if (k.getName().equalsIgnoreCase(liste.get(i).getName())
// && k.getSurname().equalsIgnoreCase(liste.get(i).getSurname())) {
// liste.remove(i);
// }
if(k.equals(liste.get(i))) {
liste.remove(i);
}
}
I recommend you to simply do something like this;
liste.remove(liste.indexOf(k));
This returns -1 if k is not found in liste
You can use that return value instead of matching liste.size() == 6
, if that suits your use case as well.
There may be other suggestions possible, but I guess more information will be required about your code as mentioned in the comments. Hope this helps!