Returning searched results in an array in Java without ArrayList

Posted by Crystal on Stack Overflow See other posts from Stack Overflow or by Crystal
Published on 2010-04-29T02:14:38Z Indexed on 2010/04/29 2:27 UTC
Read the original article Hit count: 327

Filed under:

I started down this path of implementing a simple search in an array for a hw assignment without knowing we could use ArrayList. I realized it had some bugs in it and figured I'd still try to know what my bug is before using ArrayList. I basically have a class where I can add, remove, or search from an array.

public class AcmeLoanManager 
{
    public void addLoan(Loan h)
    {
        int loanId = h.getLoanId();
        loanArray[loanId - 1] = h;
    }


    public Loan[] getAllLoans()
    {
        return loanArray;
    }


    public Loan[] findLoans(Person p)
    {
        //Loan[] searchedLoanArray = new Loan[10]; // create new array to hold searched values
        searchedLoanArray = this.getAllLoans(); // fill new array with all values

        // Looks through only valid array values, and if Person p does not match using Person.equals()
        // sets that value to null.
        for (int i = 0; i < searchedLoanArray.length; i++) {
            if (searchedLoanArray[i] != null) {
                if (!(searchedLoanArray[i].getClient().equals(p))) {
                    searchedLoanArray[i] = null;
                }
            }
        }
        return searchedLoanArray;
    }

    public void removeLoan(int loanId)
    {
        loanArray[loanId - 1] = null;
    }

    private Loan[] loanArray = new Loan[10]; 
    private Loan[] searchedLoanArray = new Loan[10]; // separate array to hold values returned from search
}

When testing this, I thought it worked, but I think I am overwriting my member variable after I do a search. I initially thought that I could create a new Loan[] in the method and return that, but that didn't seem to work. Then I thought I could have two arrays. One that would not change, and the other just for the searched values. But I think I am not understanding something, like shallow vs deep copying???....

© Stack Overflow or respective owner

Related posts about java