简体   繁体   中英

.java uses unchecked and unsafe operation

here is my java code:

import javax.swing.*;

public class Employee1 extends JFrame {

    JPanel panel;
    JLabel l1;
    JList list;

    public Employee1() {
        super("Employee Details");
        panel = new JPanel();
        l1 = new JLabel("City : ");
        String cities[] = {"Mumbai", "Delhi", "Madras"};
        list = new JList(cities);
        panel.add(l1);
        panel.add(list);
        getContentPane().add(panel);
        setSize(400, 400);
        setVisible(true);
    }

    public static void main(String args[]) {
        Employee1 obj = new Employee1();
    }
}

this code gives me warning .java uses unchecked and unsafe operation. i have exams so please help me to go through it .

You should make use of a type parameter for your JList because this is a generics error and JList supports genercis.

Change:

JList list to JList<String> list
and list = new JList(cities) to list = new JList<>(cities)

public class Employee1 extends JFrame {
    private final JPanel panel;
    private final JLabel l1;
    private final JList<String> list;    // <--- first change

    public Employee1() {
        super("Employee Details");

        final String[] cities = {"Mumbai", "Delhi", "Madras"};

        panel = new JPanel();
        l1    = new JLabel("City : ");
        list  = new JList<>(cities);     // <--- second change

        panel.add(l1);
        panel.add(list);
        getContentPane().add(panel);

        setSize(400, 400);
        setVisible(true);
    }    
}

See Lesson: Generics for information and examples on this topic

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