Skip to content

Commit 547b47d

Browse files
committed
added equals, hashCode and toString implementations to fj.List<A> which delegate to the corresponding Equal, Hash and Show classes which use the member values, see functionaljava#14
1 parent b8fb621 commit 547b47d

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

core/src/main/java/fj/data/List.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,13 @@
77
import fj.F2;
88
import fj.F3;
99
import fj.Function;
10+
import fj.Hash;
1011
import fj.Monoid;
1112
import fj.Ord;
1213
import fj.P;
1314
import fj.P1;
1415
import fj.P2;
16+
import fj.Show;
1517
import fj.Unit;
1618
import static fj.Function.curry;
1719
import static fj.Function.constant;
@@ -1828,4 +1830,45 @@ private void copy() {
18281830
snoc(t.head());
18291831
}
18301832
}
1833+
1834+
/**
1835+
* Perform an equality test on this list which delegates to the .equals() method of the member instances.
1836+
* This is implemented with Equal.listEqual using the anyEqual rule.
1837+
*
1838+
* @param obj the other object to check for equality against.
1839+
* @return true if this list is equal to the provided argument
1840+
*/
1841+
//Suppress the warning for cast to <code>List<A></code> because the type is checked in the previous line.
1842+
@SuppressWarnings({ "unchecked" })
1843+
@Override public boolean equals( final Object obj ) {
1844+
if ( obj == null || !( obj instanceof List ) ) { return false; }
1845+
1846+
//Casting to List<A> here does not cause a runtime exception even if the type arguments don't match.
1847+
//The cast is done to avoid the compiler warning "raw use of parameterized class 'List'"
1848+
return Equal.listEqual( Equal.<A>anyEqual() ).eq( this, (List<A>) obj );
1849+
}
1850+
1851+
/**
1852+
* Compute the hash code from this list as a function of the hash codes of its members.
1853+
* Delegates to Hash.listHash, using the anyHash() rule, which uses the hash codes of the contents.
1854+
*
1855+
* @return the hash code for this list.
1856+
*/
1857+
@Override public int hashCode() {
1858+
return Hash.listHash( Hash.<A>anyHash() ).hash( this );
1859+
}
1860+
1861+
/**
1862+
* Obtain a string representation of this list using the toString implementations of the members. Uses Show.listShow with F2 argument and may
1863+
* not be very performant.
1864+
*
1865+
* @return a String representation of the list
1866+
*/
1867+
@Override public String toString() {
1868+
return Show.listShow( Show.<A>anyShow() ).show( this ).foldLeft( new F2<String, Character, String>() {
1869+
@Override public String f( final String s, final Character c ) {
1870+
return s + c;
1871+
}
1872+
}, "" );
1873+
}
18311874
}

0 commit comments

Comments
 (0)