javajava-streamresultsetclasscastexceptiondate-range

ClassCastException converting a DateRange[] to an Array using streams


I tried to transform a DateRange[] into an Array with streams, but it gives me a ClassCastException error

Array pgArray = rs.getArray("periodo_carica");
periodo_carica = (DateRange[]) pgArray.getArray();
List<DateRange> periodo_carica2 = new ArrayList<DateRange>();
periodo_carica2 =
                 Arrays.stream(periodo_carica)
                 .map(DateRange2::getRange)
                 .filter(d -> DateRange2.getRange(d) != null)
                 .collect(Collectors.toList());

Output:

Connected to PostgreSQL server successfully!
Exception in thread "main" java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to 
 class [Lorg.jfree.data.time.DateRange; ([Ljava.lang.Object; is in module java.base of loader 
'bootstrap'; [Lorg.jfree.data.time.DateRange; is in module jfreechart@1.5.0 of loader 'app')

In my database in PostgreSQL I have the table, in Java in Eclipse I created the corresponding attribute DateRange[] that YOU TOLD ME TO SET AS OBJECT[] BUT it is DateRange[]

CREATE TABLE public.parlamentari
(
nome character varying(100) COLLATE pg_catalog."default" NOT NULL,
partito character varying(100) COLLATE pg_catalog."default" NOT NULL,
circoscrizione character varying(100) COLLATE pg_catalog."default" NOT NULL,
data_nascita date,
luogo character varying(100) COLLATE pg_catalog."default",
titolo_studi character varying(100) COLLATE pg_catalog."default",
mandati character varying(1000)[] COLLATE pg_catalog."default",
commissioni character varying(100)[] COLLATE pg_catalog."default",
periodo_carica daterange[],
CONSTRAINT parlamentari_pkey PRIMARY KEY (nome, partito, circoscrizione),
CONSTRAINT parlamentarinomekey UNIQUE (nome)
 ,
CONSTRAINT parlamentaripartitonomekey UNIQUE (partito, nome)

 )

Solution

  • The error message tell us that the value returned from the getArray() call is an Object[], not a DateRange[]. Sure, all the objects in the array might be DateRange objects, but the array component type is Object, not DateRange, so you'll have to cast twice.

    Array pgArray = rs.getArray("periodo_carica");
    Object[] periodo_carica = (Object[]) pgArray.getArray(); // cast to Object[]
    List<DateRange> periodo_carica2 = new ArrayList<DateRange>();
    periodo_carica2 =
                    Arrays.stream(periodo_carica)
                    .map(o -> (DateRange) o) // cast each element to DateRange
                    .map(DateRange2::getRange)
                    .filter(d -> DateRange2.getRange(d) != null)
                    .collect(Collectors.toList());