David:
Tengo dos clases "Haus" y "Wohnung". Las puse en un ArrayList separada. ¿Puedo comparar dos ArrayList de objetos diferente, que es más barato, por ejemplo: "Wohnung" precio de 20.000 dólares y "Haus" precio de 30.000 dólares?
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());
}
}
Nishntcl527:
Puede anular el método equals tanto de los objetos. Puede hacerlo de esta manera:
class A {
public boolean equals(Object other) {
// return whatever you want depending on what you want in order for that to be equal.
}
}
En caso de que eres, por supuesto, que se pondría en estás Haus
y Wohung
clases. Por ejemplo, si usted está comparando precios, usted puede hacer esto:
class Haus {
public boolean equals(Object other) {
// I won't show how to safely down-cast.
Wohung w = (Wohung) other;
return w.price == price;
}
}
Y lo mismo para la otra clase, excepto el interruptor Wohung
a Haus
. El ArrayList
llamará al método es igual, y será igual si ovveride el equals
método correctamente.
Pero siempre puede iterar a través de ambas listas si no quiere ovveride el método es igual.
// 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;