简体   繁体   中英

How to remove "unchecked generics array creation for varargs" in XYChart on JavaFX?

I am studying JavaFX and I am also a newbie in Java. (I am using Java8 in Windows.)

Sample code is like below.

XYChart.Series series1 = new XYChart.Series();
eries1.setName("남자");
series1.setData(FXCollections.observableArrayList(
        new XYChart.Data("2015", 70),
        new XYChart.Data("2016", 40),
        new XYChart.Data("2017", 50),
        new XYChart.Data("2018", 30)
));

In this code, I can see a warning. That is,

Unchecked call to 'Data(X, Y)' as a member of raw type 'javafx.scene.chart.XYChart.Data'

Though the code works, I want to remove this warning because I am weak at Java generics programming and want to learn more about it through sample code.

What is the right way of removing that warning?

Thank you.

Change the lines that look like

new XYChart.Data("2015", 70)

to specify an inferred generic type using the "diamond operator" <> . Like,

new XYChart.Data<>("2015", 70)

and if using an older version of Java (without the diamond operator), provide the <X,Y> type parameters documented in XYChart.Data like

new XYChart.Data<String, Integer>("2015", 70)

The following gives no warnings with java 12

XYChart.Series<String, Integer> series1 = new XYChart.Series<>();
ObservableList<XYChart.Data<String, Integer>> list = FXCollections.observableArrayList();
list.add(new XYChart.Data<>("2015", 70));
list.add(new XYChart.Data<>("2016", 40));
list.add(new XYChart.Data<>("2017", 50));
list.add(new XYChart.Data<>("2018", 30));
series1.setData(list);

See my last comment to Elliot's answer. Basically you can't get rid of the warning (other than using the annotation @SuppressWarning ) when using method addAll() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM