比较两种通用的ArrayList-java
我有两个班“豪斯”和“沃农”。我把它们放在一个单独的数组列表中。 我可以比较两个不同的ArrayList哪个对象更便宜,例如:“Wohnung”价格20000美元 “豪斯”的价格是30000美元比较两种通用的ArrayList-java,java,Java,我有两个班“豪斯”和“沃农”。我把它们放在一个单独的数组列表中。 我可以比较两个不同的ArrayList哪个对象更便宜,例如:“Wohnung”价格20000美元 “豪斯”的价格是30000美元 import java.util.ArrayList; import java.util.Scanner; public class mainW { public static void main(String[] args) { Scanner sc = new Scanner(S
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());
}
}
import java.util.ArrayList;
导入java.util.Scanner;
公共类mainW{
公共静态void main(字符串[]args){
扫描仪sc=新的扫描仪(System.in);
System.out.println(“您的固定资产是多少?”);
ArrayListWohnungListe=新的ArrayList();
ArrayListHausListe=新的ArrayList();
int anzhl=sc.nextInt();
int i=0;
双x,y;
国际扎尔;
而(i
Java文档说明:
“如果两个列表包含相同的元素,则它们被定义为相等
按相同顺序”
因此,WohnungListe.equals(HausListe)
将始终为false
如果要通过某个公共字段(例如价格)比较WohnungListe和HausListe,请迭代这两个列表并分别比较每一对。您可以覆盖这两个对象的equals方法。您可以这样做:
class A {
public boolean equals(Object other) {
// return whatever you want depending on what you want in order for that to be equal.
}
}
当然,在你的情况下,这将被放在你的Haus
和Wohung
类中。例如,如果您正在比较价格,则可以执行以下操作:
class Haus {
public boolean equals(Object other) {
// I won't show how to safely down-cast.
Wohung w = (Wohung) other;
return w.price == price;
}
}
另一个类也一样,除了将Wohung
切换到Haus
。ArrayList
将调用equals方法,如果正确验证equals
方法,它将是相等的
但是,如果不想验证equals方法,您可以始终迭代这两个列表
// 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;
//我假设它们大小相等。
对于(int i=0;i
你可以让它们有一个包含价格的公共超类。这样你就可以对它们进行排序和比较,而不管它们是房子还是公寓。当我测试这个时:System.out.println(WohnungListe.equals(HausListe));然后它返回true。在调用equals()之前,确保两个列表都不是空的。