Compare two generic ArrayList - java

David :

I have two Classes "Haus" and "Wohnung" . I put them in a separate ArrayList. Can i compare two different ArrayList which Object is cheaper for example: "Wohnung" price 20000 Dollar and "Haus" price 30000 Dollar?

import java.util.ArrayList;
import java.util.Scanner;

public class mainW {

    public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Wie viele Immobilien wollen Sie vergleichen?");
    ArrayList<Wohnung>WohnungListe = new ArrayList<>();
    ArrayList<Haus>HausListe = new ArrayList<>();

    int anzhl = sc.nextInt();
    int i = 0;
    double x, y ;
    int zahl;
    while (i < anzhl) {
        System.out.println("Ist diese Wohnung was ? (1) wenn Wohnung (2) wenn Haus ");
        zahl = sc.nextInt();
        if(zahl ==1) {
            System.out.println("Welche W1 Kooridante ");
            x = sc.nextDouble();
            System.out.println("Welche W2 Kooridante ");
            y =sc.nextDouble();
            Wohnung w = new Wohnung(x,y);
            WohnungListe.add(w);
            i++;
        }
        if(zahl ==2) {
            System.out.println("Welche H1 Kooridante ");
            x = sc.nextDouble();
            System.out.println("Welche H2 Kooridante ");
            y =sc.nextDouble();
            Haus h = new Haus(x,y);
            HausListe.add(h);
            i++;
        }
    }   
    if(WohnungListe.equals(HausListe)) {
        System.out.println("Fan");
    }
        System.out.println("Wohnung "+WohnungListe.toString());
        System.out.println("Haus "+HausListe.toString());
    }
}
nishantc1527 :

You can override the equals method of both the objects. You can do it like this:

class A {
    public boolean equals(Object other) {
        // return whatever you want depending on what you want in order for that to be equal.
    }
}

In you're case, of course, that would be put in you're Haus and Wohung classes. For example, if you're comparing prices, you can do this:

class Haus {
    public boolean equals(Object other) {
        // I won't show how to safely down-cast.
        Wohung w = (Wohung) other;
        return w.price == price;
    }
}

And the same for the other class, except switch Wohung to Haus. The ArrayList will call the equals method, and it will be equal if you ovveride the equals method correctly.

But you can always just iterate through both lists if you don't want to ovveride the equals method.

                 // I'm going to assume they are of equal size.
for(int i = 0; i < WohungListe.size(); i ++) {
    if(! (/* Check if they are equal */) {
        return false;
    }
}

return true;

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=378676&siteId=1