简体   繁体   中英

Java: Compare two class list regardless of order

If you have Two class list how can you compare them to see if they are the same regardless of order.

Class[] list1[class1, class1, class2]
Class[] list2[class2, class1, class1]

These list are the same regardless of order but how can java Boolean this? eg

if(list1.sort == list2.sort){}

The best solution will be to add Guava and use MultiSet .

HashMultiset<Class> hms1 = new HashMultiSet<>();
HashMultiset<Class> hms1 = new HashMultiSet<>();
for (Class c : list1) {
    hms1.add(c);
}
for (Class c : list2) {
    hms2.add(c);
}
if (hms1.equals(hms2) {
    //lists are the same in your understanding of the same
}

Simpler solution would be to use Map<Class, Integer>

HashMap<Class, Integer> hm1 = new HashMap<>();
HashMap<Class, Integer> hm2 = new HashMap<>();
for (Class c : list1) {
    if (!hm1.containsKey(c)) {
        hm1.put(c, 1);
    } else {
        hm1.put(c, hm1.get(c)+1);
    }
}
for (Class c : list2) {
    if (!hm2.containsKey(c)) {
        hm2.put(c, 1);
    } else {
        hm2.put(c, hm2.get(c)+1);
    }
}
if (hm1.equals(hm2) {
    //lists are the same in your understanding of the same
}
    Class<?>[] list1 = new Class[] { String.class, String.class, Integer.class };
    Class<?>[] list2 = new Class[] { Integer.class, String.class, String.class };

    Comparator<Class<?>> classComparator = new Comparator<Class<?>>() {

        @Override
        public int compare(Class<?> o1, Class<?> o2) {
            return o1.getCanonicalName().compareTo(o2.getCanonicalName());
        }
    };

    Arrays.sort(list1, classComparator);
    Arrays.sort(list2, classComparator);

    if (Arrays.equals(list1, list2)) {
        System.out.println("same regardless of order");
    } else {
        System.out.println("NOT same regardless of order");
    }

The above prints

same regardless of order

I am modifying the original lists. You may want to take copies first if this is not desired.

Arrays.equals() is using Class.equals() , which in turn is just Object.equals() . As long as there is only one Class object for each Class, this works. I believe that this holds true as long as you are using only one class loader. So be warned that it's a bit subtle here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM