vbhvbhurke
vbhvbhurke

Reputation: 3

.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.

Upvotes: 0

Views: 6603

Answers (1)

ifloop
ifloop

Reputation: 8386

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

Upvotes: 3

Related Questions