Я пытаюсь вызвать метод showArrayList, но он продолжает выдавать мне ContactList, который не может быть преобразован в java.util.ArrayList<Contact>. Что я делаю неправильно? Пока у меня это:

public class ControlPanel extends JPanel implements ActionListener
{
    // Fields (instance variables/attributes)
    private JLabel      phoneNumberLabel;  // a reference to the phoneNumberLabel that is displayed in the PhoneNumberDisplayPanel.

    private Contact     nameAndNumber;    // Holds the name and number for a phone Contact.
    // Contact lists;
    private ContactList contacts;          // Encapsulates a list of saved contacts, ie.e phone Contacts.
    private ContactList callsMade;         // Encapsulates a list of calls made, i.e. phone Contacts.

private void findNumber( )
    {
        if(nameLabel.getText(  ).equals(contacts.searchByName(nameLabel.getText())))
            showArrayList(contacts,nameLabel.getText());
        else
            showArrayList(contacts, "");
    }

Метод showArrayList:

public void showArrayList( ArrayList<Contact> list, String title ) 
    {
        int x = 410;
        int y = 445;
        int width  = 350;
        int height = 200;
        boolean disableCloseButton = false;
        Window newWindow  = new Window( title, x, y, width, height, Color.RED, disableCloseButton );
        {
            newWindow.println( "No contact information saved" );
        }
        else
        {
            for ( Contact c: list )
            {
                newWindow.println( c.toString() );
            }
        }

Теперь я сделал это, и он компилируется:

private void findNumber( )
    {
        ArrayList<Contact> list = new ArrayList<Contact>();
        if(nameLabel.getText().equals(contacts.searchByName(nameLabel.getText())))
            showArrayList(list,nameLabel.getText());
        else
            showArrayList(list, "");
    }

Мой класс ContactList:

public class ContactList
{
    private ArrayList<Contact> list;

    /**
     * Constructor for a ContactList, to initialize the list from file.
     * 
     * @param  fileName   a reference to an existing file
     * @param  window     a reference to an existing window to display the list contacts
     */
    public ContactList( String fileName, Window window )
    {
        list = new ArrayList<Contact>( );

        File file = new File( fileName );

        // Remark. A file needs to have been written, before it can be read.
        if (file.exists())
        {
            try
            {
                Scanner fileReader = new Scanner( file ); 
                readFile( fileReader );
                window.print( this.toString () );
            }
            catch( FileNotFoundException error )   // could not find file
            {
                System.out.println( "File not found " );
            }
        }
    }

    /********************************************************************
     * Searches the list for a particular contact, 
     * comparing this name and number (in lower case) 
     * with the contact name and number (in lower case).
     * 
     * @param   contact
     * @return  returns true if the contact is found, otherwise false
     */
    public boolean found( Contact contact )
    {  
        for(Contact c: list){
            if(c == contact){
                return true;
            }   
        }
        return false;

    }

    /******************************************************************
     * Adds one contact to the list
     * 
     * @param   contact
     */
    public void add( Contact contact )
    {
        list.add(contact);


    }

    /******************************************************************
     * searches the list for each name that contains the specified substring
     * 
     * @param   substring
     * @return  returns the result as an ArrayList
     */
    public ArrayList<Contact> searchByName(String substring) 
    {
        ArrayList<Contact> l = new ArrayList<Contact>( );
        for(Contact c: list){
            if(c.getName() == substring){
                l.add(c);   
            }
        }
        return l;   
    }
1
phoenix47 9 Ноя 2014 в 07:58
Покажите нам, где вы объявляете contacts
 – 
Vince
9 Ноя 2014 в 08:01
Отредактируйте его в своем вопросе, а не как комментарий (трудно читать как комментарий). contacts – это ContactList, а не ArrayList<Contact>, поэтому ваш метод его не принимает.
 – 
Vince
9 Ноя 2014 в 08:08
Я пробовал все. Я попробовал свой настоящий ArrayList (из моего класса ContactList). Может быть, мне следует создать новый ArrayList?
 – 
phoenix47
9 Ноя 2014 в 08:11
Покажите, где вы пытались использовать ArrayList
 – 
Vince
9 Ноя 2014 в 08:13
Это не список из вашего объекта ContactList; это совершенно новый список. Вы не должны получить ошибку, сделав это, хотя вы не получите доступ к нужным значениям, поскольку это неправильный список. Ваш ContactList должен иметь ArrayList с методом доступа к нему (если он частный)
 – 
Vince
9 Ноя 2014 в 08:26

2 ответа

ContactList не расширяет ArrayList<Contact>, поэтому вы не можете передать его в качестве аргумента вашему методу, который ожидает ArrayList<Contact>. Возможно, у вас может быть getter в ContactList, чтобы выставить list, чтобы вы могли передать его своему методу showArrayList, или вы можете реализовать showArrayList метод, который принимает тип ContactList argument.

0
sTg 9 Ноя 2014 в 09:07
private void findNumber( )
    {
        if(nameLabel.getText().equals(contacts.searchByName(nameLabel.getText())))
            showArrayList(contacts.searchByName(""),nameLabel.getText());
        else
            showArrayList(contacts.searchByName(""), "");
    }
0
phoenix47 9 Ноя 2014 в 09:21