方法toArray()不在列表上工作

时间:2013-10-07 17:54:03

标签: java arrays list

我正在尝试将列表转换为数组,但是我收到错误,我无法弄清楚原因。我正在接受当前时间并且在for循环中我得到了今天剩余的时间并将其放入列表中。当我尝试将其更改为数组时,我收到错误。我尝试这样做是因为稍后我在JCombobox

中使用该数组
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.GregorianCalendar;
import java.util.Calendar;

public class Frame extends JFrame implements ActionListener{
    //JFrame elements
    private JButton btnSetTime;
    private JLabel lblTitle;
    private JComboBox comboTime;

    //Standard elements
    private Timer tillPopup, tillShutdown;

    Calendar calendar = new GregorianCalendar();
    int hour = (calendar.get(Calendar.HOUR_OF_DAY));
    List times = createDropdown(hour);
    // Convert ArrayList to array which can be used in the combobox
    String[] dropdownElements = times.toArray();

    String[] a = {"a","b"};
    public Frame(){
        setLayout(new FlowLayout());

        //Labels
        lblTitle = new JLabel("Deze applicatie sluit u computer automatisch af om het energieverbruik te verminderen.");

        //Combobox
        comboTime = new JComboBox(a);
        comboTime.setSelectedIndex(0);

        //Button
        btnSetTime = new JButton("Zet afsluittijd");

        //Timers
        //tillPopup = new Timer(this);
        //tillShutdown = new Timer(this);

        //Add elements to Frame
        add(lblTitle);
        add(comboTime);
        add(btnSetTime);

        //Add actionListeners
        btnSetTime.addActionListener(this);

        setSize(500,300);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
    private List createDropdown(int hour){
        List availableHours = new List();
        for(int i = hour; i <=24; i++){
            if (i != 24){
                availableHours.add(i + ":00");
            }
            else if(i == 24){
                availableHours.add("00:00");
            }
        }
        return availableHours;
    }
    public void actionPerformed(ActionEvent e){
        if (e.getSource() == btnSetTime){
            Object popupTime = comboTime.getSelectedItem();
                System.out.println(popupTime);

        }
    }
}

我收到以下错误:

Frame.java:21: error: cannot find symbol  
String[] dropdownElements = times.toArray();  
                                 ^  
    symbol:   method toArray()  
    location: variable times of type List

如何更改从method createDropdown返回数组的列表以及为什么我做错了?

1 个答案:

答案 0 :(得分:5)

由于您已导入import java.awt.*;,因此使用的Listjava.awt.List。您需要添加导入 - java.util.List

请不要使用原始类型List。在较新的代码中不建议使用原始类型。当然你不会注意到它,因为java.awt.List是一个非泛型类。所以即使编译器也不会给你一个警告信息。

您应该在您的情况下使用参数化类型 - List<String>。将您的方法修改为:

private List<String> createDropdown(int hour){
    List<String> availableHours = new ArrayList<String>();
    ...
}

您还需要添加import java.util.ArrayList