list - How to check whether a value is already in an arraylist before inserting it in Java? -
i want insert values list, if values aren't in it. code far creates infinite loop because add values list, size of list increases there no way terminating condition for loop met. part of larger program, e type of object extends point. note that: e extends point. e has value (in addition cor-ordinates inherits point). if list empty, i'd store e in list. list of type e. if list not empty, check see if e same point location e entering exists in list. don't check e object rather check whether x , y values match. updated code:
list<e> listclosestfirst = new linkedlist<e>(); if (listclosestfirst.isempty()) { listclosestfirst.add(e); } else { (int = 0; < listclosestfirst.size(); i++) { if ((e.getlocation()).equals((listclosestfirst.get(i)).getlocation())) { // nothing, move on } // end if else { listclosestfirst.add(e); } } // end loop } // end else statement system.out.println("closest first memory: " + listclosestfirst);
boolean exist = false; listiterator<e> iterator = listclosestfirst.listiterator(0); while (iterator.hasnext() && !exist) { exist = (e.getlocation()).equals((iterator.next()).getlocation()); } if (!exist) { listclosestfirst.add(e); }
since you're using linkedlist, iterator more efficient. approximately, enhanced o(n!) o(n).
Comments
Post a Comment