Skip to content

Commit

Permalink
Added CollectionUtils performance fix (#656)
Browse files Browse the repository at this point in the history
  • Loading branch information
marianbuenosayres authored and mswiderski committed Nov 4, 2016
1 parent e04f1b0 commit 12dabfd
Showing 1 changed file with 16 additions and 29 deletions.
Expand Up @@ -20,6 +20,7 @@
import java.io.ObjectInput; import java.io.ObjectInput;
import java.io.ObjectOutput; import java.io.ObjectOutput;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;


Expand Down Expand Up @@ -50,54 +51,40 @@
public class CollectionUtils { public class CollectionUtils {


public static boolean equals(List list1, List list2) { public static boolean equals(List list1, List list2) {
if ( list1 == null && list2 == null ) { if ( list1 == list2 ) {
// both are null //both are the same
return true; return true;
} }

if ( list1 == null || list2 == null ) { if ( list1 == null || list2 == null ) {
// we know both aren't null, so if one is null them obviously false // we know both aren't null, so if one is null them obviously false
return false; return false;
} }

if ( list1.size() != list2.size() ) { if ( list1.size() != list2.size() ) {
return false; return false;
} }

if ( list1.isEmpty() ) {
if ( list1.isEmpty() && list2.isEmpty() ) {
return true; return true;
} }

ArrayList<?> arr = new ArrayList<>(list2);

for ( Object obj : list1 ) {
for ( Object item1 : list1) { if ( !arr.remove( obj ) ) {
boolean exists = false;
for ( Object item2 : list2 ) {
if ( item1.equals( item2 )) {
exists = true;
break;
}
}
if ( !exists ) {
return false; return false;
} }
} }

return true; return true;
} }


public static int hashCode(List list) { public static int hashCode(List list) {
if ( list == null ) { if ( list == null ) {
return 0; return 0;
} }

if ( list.isEmpty() ) {
final int prime = 31; return 1;
int result = 1; }
for ( Iterator it = list.iterator(); it.hasNext(); ) { ArrayList<?> tmp = new ArrayList<>(list);
Object next = it.next(); Collections.sort(tmp, (o1, o2) -> Integer.compare(o1.hashCode(), o2.hashCode()));
result = prime * result + ((next == null)? 0 : next.hashCode()); return tmp.hashCode();
} }
return result;
}


public static void writeCommentList(List<Comment> list, ObjectOutput out) throws IOException { public static void writeCommentList(List<Comment> list, ObjectOutput out) throws IOException {
out.writeInt( list.size() ); out.writeInt( list.size() );
Expand Down

0 comments on commit 12dabfd

Please sign in to comment.