简体   繁体   中英

How to compare 2 array without using any methods from the java arrays or collections class?

This is a part of my homework assignment so I need explanation and not just an answer.

I'm creating the legendary purse class. I have to be able to compare one purse(array) to another purse(array). The kicker is that I can't use any methods from the java arrays or collections class. Where do I even start on creating something like this?

An example of what im doing is this:

String[] array1 = {"Quarter", "Dime", "Nickel", "Penny"};
String[] array1 = { "Dime", "Quarter", "Penny", "Nickel"};
(Does Array1==Array2?)
return true/false

Again I need to understand this so please don't just figure it out for me, but throw me some ideas.

You could try nested for loops. In pseudo-code:

for each element 'i' in Array1:
    for each element 'j' in Array2:
        does 'i' equal 'j'?
            // do something
        else:
            // do something else

Does this get you started? Would you like more help?

The way you'd compare elements between two arrays without Arrays.equal() would be to iterate over each element and compare them one at a time.

String[] array1 = new String[] {"Quarter", "Dime", "Nickel", "Penny"};
String[] array2 = new String[] {"Dime", "Penny", "Quarter", "Nickel"};

public boolean equalArrays(String[] array1, String[] array2) {
    if(array1.length != array2.length) {
        return false;
    }
    int matched = 0;
    for(int i = 0; i < array1.length; i++) {
        for(int j = 0; j < array2.length; j++) {
            if(array2[j].equals(array1[i])) {
                matched++;
                break;
            }
        }
    }
    return matched == array1.length;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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