Merge pull request #10478 from sk1418/uncheckedCast

unchecked cast warning article
This commit is contained in:
Eric Martin 2021-02-20 16:40:01 -06:00 committed by GitHub
commit 4c8c9d2456
2 changed files with 51 additions and 0 deletions

View File

@ -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;
}
}

View File

@ -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")));
}
}