1

I have a class

class User{
   String territory;
   String company;
   String name;
}

I have an arraylist of 'User' . I would like to lookup a User object from the list using the String 'territory+company' . The lookup should be based on Binary search. How could i implement it?

The Collections.binarySearch() needs us to create a dummy User object. I dont want that.

3
  • 1
    show us what you have tried.. Commented Dec 15, 2016 at 7:34
  • 1
    Possible duplicate of Implement binary search in objects Commented Dec 15, 2016 at 7:35
  • @AnoopLL I have tried Collections.binarySearch. But that requires a dummy object creation. I dont want that. Commented Dec 15, 2016 at 7:39

1 Answer 1

0

All you need is to implement the Comparable interface for your User class. Then you can use Collections.binarySearch() method (only if your list is sorted of course).

Something like that would work for you:

    public static void main(String[] args) {
        List <User> list = new ArrayList<>();
        list.add(new User("A1", "B1", "Name1"));
        list.add(new User("A2", "B2", "Name2"));
        list.add(new User("A3", "B3", "Name3"));
        list.add(new User("A4", "B4", "Name4"));
        list.add(new User("A5", "B5", "Name5"));

        System.out.println(list.get(Collections.binarySearch(list, new User("A4", "B4", "Name4"))));
    }


    static class User implements Comparable <User>{
        String territory;
        String company;
        String name;

        public User(String territory, String company, String name) {
            this.territory = territory;
            this.company = company;
            this.name = name;
        }

        @Override
        public int compareTo(User o) {
            return (territory+company).compareTo(o.territory+o.company);
        }

        @Override
        public String toString(){
            return territory + "," + company + "," + name;
        }
    }
Sign up to request clarification or add additional context in comments.

3 Comments

The OP was made more complete: "The Collections.binarySearch() needs us to create a dummy User object. I dont want that.". So this one no longer answers the question.
Did you got the answer. I also need the same.
the question explicitly asks for not having to create a dummy User object But your answer creates it, you are not really answer this case

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.