简体   繁体   English

ArrayList.add()不添加,不返回错误

[英]ArrayList.add() not adding, not returning errors

For my AP CompSci class, we're making a "Contacts" program to simulate using a virtual phonebook. 对于我的AP CompSci类,我们正在制作一个“联系人”程序以使用虚拟电话簿进行模拟。 The main class, Contacts is as follows. 主要类别Contacts如下。

public class Contacts extends ArrayList<Contact>
{
    private ArrayList<Contact> contacts = new ArrayList<Contact>(); 

    @Override
    public boolean add(Contact c)
    {
        contacts.add(c);
        Collections.sort(contacts);
        return true;
    }

    public ArrayList<Contact> search(String name)
    {
        ArrayList<Contact> temp = new ArrayList<Contact>();
        for(int i = 0; i<=contacts.size(); i++)
        {
            if(contacts.get(i).getName().equals(name))
            {
                temp.add(new Contact(name));
            }
        }

        return temp;
    }

}

As you can see, it extends ArrayList<Contact> . 如您所见,它扩展了ArrayList<Contact> Contact is a simple object, composed of a String name and a 7-integer int num . Contact是一个简单的对象,由String name和7整数int num The problem lies in the class ContactsFactory , where I loop through a text file to create a huge ArrayList of names. 问题出在ContactsFactory类中,在其中循环遍历文本文件以创建巨大的ArrayList名称。

public class ContactsFactory {
    public static Contacts getContacts() throws FileNotFoundException {
        String path = System.getProperty("user.dir");
        Scanner s = new Scanner(new File(path + "\\src\\names.txt"));
        Contacts contacts = new Contacts();
        do {
            contacts.add(new Contact(s.next()));
        } while (s.hasNext());

        s.close();

        //print size to see anything added. It returns 0.
        System.out.println(contacts.size());
        return contacts;
    }
}

However, when I implement the add() method for each name, not only does it seem not to add anything, but it returns no error. 但是,当我为每个名称实现add()方法时,不仅看起来没有添加任何内容,而且没有返回错误。 Even more interesting is that, as I found out when I put a print statement after every iteration, s.next() is no empty String. 更加有趣的是,正如我在每次迭代后放置一条打印语句时所发现的那样,s.next()不是空字符串。 But the String(which experiences no issues being transferred from names.txt ) is not added to contacts , and as a result, the ArrayList ends up empty with a size() of 0. 但是String(不会从names.txt传输任何问题的字符串)没有添加到contacts ,因此ArrayList最终为空, size()为0。

I think the error might be in the overridden Contacts.add() method, but I haven't been able to figure anything out. 我认为错误可能出在重写的Contacts.add()方法中,但我还无法弄清任何东西。 Can someone help me out? 有人可以帮我吗? Thanks in advance. 提前致谢。

I'm wondering why you extend ArrayList and additionally keep another copy of an ArrayList around. 我不知道为什么你扩展ArrayList ,另外一个保持的另一个副本ArrayList周围。 Besides the overwritten add (and size from azurefrog's answer), an ArrayList as well as the List interface offers a bunch of other methods - instead of overwriting all of them and delegating to the internal list, I would just rely on those methods and add the functionality I need: 除了被覆盖的add (和azurefrog的答案的size )之外, ArrayList以及List接口还提供了许多其他方法-而不是覆盖所有方法并委派给内部列表,我将仅依靠这些方法并添加我需要的功能:

public class Contacts extends ArrayList<Contact>
{
    @Override
    public boolean add(Contact c)
    {
        boolean result = super.add(c);
        Collections.sort(this);
        return result;
    }

    public ArrayList<Contact> search(String name)
    {
        // ...
    }

} }

By that you have a full-blown ArrayList and can extend it with what you need. 这样,您将拥有一个成熟的ArrayList并可以根据需要扩展它。

The other option is, to just kick out extends and just go for your own implementation of Contacts, utilizing the internal List as storage and not exposing it directly. 另一个选择是,仅展开extends并直接使用自己的Contacts实现,利用内部List作为存储而不直接公开它。

I think there is something wrong with your design. 我认为您的设计有问题。 I don't think you should extend ArrayList. 我不认为您应该扩展ArrayList。

Because when you do it, your class IS an ArrayList, and also, you created an ArrayList object inside your class. 因为执行此操作时,您的类是一个ArrayList,而且您还在类内创建了ArrayList对象。

The thing is, when you called size, original ArrayList's size is being returned. 问题是,当您调用size时,将返回原始ArrayList的大小。 Since you added the element to your ArrayList, the original is still empty. 由于您已将元素添加到ArrayList中,因此原始元素仍然为空。

You should use either delegation or inheritance, in this case you are mixing it both up. 您应该使用委托或继承,在这种情况下,您需要将两者混合使用。

Either implement java.util.List<Contact> (instead of extending ArrayList ) and delegate every method call to the delegate (the class variable contacts) 实现java.util.List<Contact> (而不是扩展ArrayList ),并将每个方法调用委托给委托(类变量contact)

OR 要么

Remove the class variable contacts and use super.add() in your add method (instead of contacts.add() ) and this instead of every other reference on contacts 删除类变量contacts并在您的add方法中使用super.add() (而不是contacts.add() ),并使用this而不是其他所有对contact的引用

I'm not sure how you read your file, but I seem to do just fine. 我不确定您如何阅读文件,但似乎还可以。 In order to access the size of the contacts object in your factory, you need to call the 'size' method on the internal ArrayList instance variable, as opposed to calling on the 'contacts' object itself. 为了访问工厂中联系人对象的大小,您需要在内部ArrayList实例变量上调用“ size”方法,而不是调用“ contacts”对象本身。 In order to properly apply the 'size' method, it maybe that you need to override this method ('size') too. 为了正确应用'size'方法,可能您也需要覆盖此方法('size')。

Other than that, adding and retrieval seems fine. 除此之外,添加和检索似乎还不错。 Check out the console output as well! 还要检查控制台输出!

public class Contacts extends ArrayList<Contact>
{
    private List<Contact> contacts = new ArrayList<Contact>(); 

    @Override
    public boolean add(Contact c)
    {
        contacts.add(c);
        //Collections.sort(contacts);
        return true;
    }

    @Override
    public String toString()
    {
        return contacts.toString();
    }

    public List<Contact> getMyList()
    {
        return this.contacts;
    }
    public static void main(String[] args)
    {
        Contacts test=ContactsFactory.getContacts();
        System.out.println(test.toString());
    }
}

class ContactsFactory {


    public static Contacts getContacts()  {

        String[] names={"A","B","C","D"};
        int i=0;

        Contacts contacts = new Contacts();
        do {
            System.out.println("Adding: "+names[i]);
            contacts.add(new Contact(names[i]));
            i++;
        } while (i<names.length);



        //print size to see anything added. It returns 0.
        System.out.println(contacts.getMyList().size());
        return contacts;
    }
}

class Contact
{
    String name;
    @Override
    public String toString()
    {
        return "Contact: "+this.name;
    }
    public Contact(String val)
    {
        this.name=val;
    }
}

Output: 输出:

Adding: A
Adding: B
Adding: C
Adding: D
4
[Contact: A, Contact: B, Contact: C, Contact: D]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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