2

I use eclipse android

I need to index or object find in ArrayList

public class myclass
{
    int id;
    int count;
    String value;
}

mainactivity
{
    ArrayList<myclass> list = new ArrayList<myclass>();
    myclass mc = new myclass();
    mc.id=1;
    mc.count=20;
    mc.value="my value 1"
    list.add(mc);
    //add 100 record in list

    //how can i this
    int index = list.find(value="search value");
    //or this
    myclass founded = list.find(value="search value");
    //or this
    myclass founded2 = list.where(a => a.value="search value").first; //yes this is linq and lambda, but i cant linq in android
}

if I use for loop, I can find index but maybe arraylist has 1billion over record and I search 1000 values in arraylist

I dont want to use 1000 times for-loop in arraylist. how can I this basicly

1
  • its even better to use a database and query the correct record whenever you need! why go for expensive arraylist and hashmaps Commented Jan 16, 2015 at 12:02

2 Answers 2

1

You can use indexOf()

int index = list.indexOf(object)
Sign up to request clarification or add additional context in comments.

1 Comment

but, object is class and I know just one variable's value in class. Ex: class: id=100, count=20, value="blue rock"; I search value="blue rock" in arraylist
0

So if you want to find 1000 values inside your 1billion ArrayList record it is better not to use ArrayList here. More preferable way for doing that is using HashMap<String, YourClass>. Where first parameter is your id and second is element of your class. You can easily found then element of your class by id. Approximately O(1).

If it is no matter how your values will be stored in ArrayList you can implements comparable interface in your class and support your collection in sorted way. So if your collection is sorted you can find your element with binary search. You should use this version of binary search

Collections.binarySearch(List<? extends T> list, T object, Comparator<? super T> comparator)

So you can implement you custom compator to check if your object is equal to something that you are finding.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.