java - How do I extract the K "smallest" elements from a list of objects? -


i'm looping through list find particular entry, assigning variable , trying remove later. it's easier demo explain.

arraylist<example> list1 = populate();  example ex1 = list1.get(0); example ex2 = ex1; list1.remove(ex2); 

i know has java's inability handle pointers, viable solution great.

edit: elaborate, brief example of code rather giving full thing. i'm doing iterating through list find lowest 10 numbers. technique go through list, find lowest , add list, remove number original list , repeat. list made of objects have int value inside them, rather list of integers.

for(0 9){     for(0 list.size){         if(list.get(x) < smallest)             smallest = list.get(x)     }     smallestlist.add(smallest);     list.remove(smallest) } 

i sort list. then, create list 10 smallest objects , change original list list1 contain remaining objects. like:

collection.sort(list1); arraylist<example> yoursmallestelements = (arraylist<example>)(list1.sublist(0, 9).clone()); list1.removeall(yoursmallestelements); 

note: cloned sublist because sublist() returns view of list list1, , that's not want here.

your class example can implement "comparable" can define how need compared. need implement method compareto(). this:

public class example implements comparable<example> {     private int integerval = <a value>;      public int compareto(example exampleobject) {         return exampleobject.integerval - this.integerval;     }    } 

have @ this link, more precisely class begins follows:

public class fruit implements comparable<fruit>{ 

Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -