Phantom
Phantom

Reputation: 119

Compare two arraylists with contains instances of classes

I want to compare two arraylists containing the instances of two separate classes with one another.

Eg: 1st list: HKY SGP 15:00 3 20:20 700

2nd list: 1 HKY SGP 8:00

so if the 1st list contains the words HKY and SGP, then the value 700 needs to be returned. Both of these are compared in a separate class called cost. I pass the arraylists to this cost class using the main method. This cost class then proceeds onto compare the arraylists.

What i have tried: I googled the problem and tried using some solutions they provided. I have tried using contains or equal. It gives me an incorrect value.

Then i tried using the get method from both the classes to compare. It does not give the desired output too.

I think i am comparing both these objects incorrectly, not sure on how to compare. Can someone shed some light on how to compare these objects in the arraylist?

Thank you!

Code in main:

    ArrayList<planes> air = new ArrayList<>();
    ArrayList<questions> q = new ArrayList(); // same as below for questions

    Scanner sc = new Scanner(System.in);
    num = sc.nextInt();


    for (int i=0; i<num; i++){  
       planes p = new planes();

       p.setfrom(sc.next());
       p.setTo(sc.next());
       p.setdT(sc.next());
       p.setaD(sc.next());
       p.setaT(sc.next());
       p.setCt(sc.next());
       air.add(p);


    }

Upvotes: 0

Views: 660

Answers (2)

imthegiga
imthegiga

Reputation: 1126

You can implement a Comparator<T>. So implementing interface will have to override its compare(T arg0, T arg1) method. At T you can put any type to compare with. Like ArrayList<>(), Class, String etc. And to check whether string contains HKY SGP; if these are always adjacent then you can directly do like:

public int compare(String list1, String list2) {

    return list1.contains("HKY SGP") && list2.contains("HKY SGP") ? 700 : 0;
}

this will return 700 if both strings contains "HKY SGP" else 0.

If "SGP" is not always after "HKY" then just check for each of them. Something like:

return list1.contains("HKY") && list1.contains("SGP") && list2.contains("HKY") && list2.contains("SGP") ? 700 : 0;

Upvotes: 0

duffymo
duffymo

Reputation: 308743

Write a custom Comparator<T> to do what you need.

Maybe a regex for both would do it:

// two Strings both contain "foo"
return x.matches("[foo]") && y.matches("[foo]");

If regex can't do it, implement your own Knuth-Morris-Pratt matcher:

http://www.ics.uci.edu/~eppstein/161/960227.html

Upvotes: 3

Related Questions