Merge pull request #10478 from sk1418/uncheckedCast
unchecked cast warning article
This commit is contained in:
commit
4c8c9d2456
|
@ -0,0 +1,26 @@
|
||||||
|
package com.baeldung.uncheckedcast;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.Month;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class UncheckedCast {
|
||||||
|
public static Map getRawMap() {
|
||||||
|
Map rawMap = new HashMap();
|
||||||
|
rawMap.put("date 1", LocalDate.of(2021, Month.FEBRUARY, 10));
|
||||||
|
rawMap.put("date 2", LocalDate.of(1992, Month.AUGUST, 8));
|
||||||
|
rawMap.put("date 3", LocalDate.of(1976, Month.NOVEMBER, 18));
|
||||||
|
return rawMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Map getRawMapWithMixedTypes() {
|
||||||
|
Map rawMap = new HashMap();
|
||||||
|
rawMap.put("date 1", LocalDate.of(2021, Month.FEBRUARY, 10));
|
||||||
|
rawMap.put("date 2", LocalDate.of(1992, Month.AUGUST, 8));
|
||||||
|
rawMap.put("date 3", LocalDate.of(1976, Month.NOVEMBER, 18));
|
||||||
|
rawMap.put("date 4", new Date());
|
||||||
|
return rawMap;
|
||||||
|
}
|
||||||
|
}
|
|
@ -0,0 +1,25 @@
|
||||||
|
package com.baeldung.uncheckedcast;
|
||||||
|
|
||||||
|
import org.junit.Assert;
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.Month;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class UncheckedCastUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenRawMap_whenCastToTypedMap_shouldHaveCompilerWarning() {
|
||||||
|
Map<String, LocalDate> castFromRawMap = (Map<String, LocalDate>) UncheckedCast.getRawMap();
|
||||||
|
Assert.assertEquals(3, castFromRawMap.size());
|
||||||
|
Assert.assertEquals(castFromRawMap.get("date 2"), LocalDate.of(1992, Month.AUGUST, 8));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = ClassCastException.class)
|
||||||
|
public void givenMixTypedRawMap_whenCastToTypedMap_shouldThrowClassCastException() {
|
||||||
|
Map<String, LocalDate> castFromRawMap = (Map<String, LocalDate>) UncheckedCast.getRawMapWithMixedTypes();
|
||||||
|
Assert.assertEquals(4, castFromRawMap.size());
|
||||||
|
Assert.assertTrue(castFromRawMap.get("date 4").isAfter(castFromRawMap.get("date 3")));
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue