1

For my AP CompSci class, we're making a "Contacts" program to simulate using a virtual phonebook. The main class, Contacts is as follows.

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>. Contact is a simple object, composed of a String name and a 7-integer int num. The problem lies in the class ContactsFactory, where I loop through a text file to create a huge ArrayList of names.

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. Even more interesting is that, as I found out when I put a print statement after every iteration, s.next() is no empty String. 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.

I think the error might be in the overridden Contacts.add() method, but I haven't been able to figure anything out. Can someone help me out? Thanks in advance.

1
  • Try extending AbstractList instead and delegate the get, set, add and size methods to your contacts variable. This way you don't need to e.g. worry about providing an Iterator yourself. Commented Apr 16, 2015 at 23:33

4 Answers 4

2

I'm wondering why you extend ArrayList and additionally keep another copy of an ArrayList around. 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:

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.

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.

Sign up to request clarification or add additional context in comments.

Comments

0

I think there is something wrong with your design. I don't think you should extend ArrayList.

Because when you do it, your class IS an ArrayList, and also, you created an ArrayList object inside your class.

The thing is, when you called size, original ArrayList's size is being returned. Since you added the element to your ArrayList, the original is still empty.

Comments

0

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)

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

Comments

0

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. In order to properly apply the 'size' method, it maybe that you need to override this method ('size') too.

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.