user1089593
user1089593

Reputation: 11

how to compare two arrays that are in different classes?

I got two arrays that i need to compare it they have the same value.

I got one Ticket class, and a NumberGenerator class.

In the Ticket class, I got an array that contain my "lucky numbers" and the NumberGeneratorcontains the winning numbers.

` public class sammenligning

{ public void jon () { if (Arrays.equals(TicketRegister.getticketReg(),LottoMachine.listOfWinningNumbers())) { System.out.println("We have a winner!"); } } } ` i get an error at the getticketReg (dnw) (ticketReg is the name of the array)

Upvotes: 1

Views: 1000

Answers (5)

subodh
subodh

Reputation: 6158

Ticket class:

public class Ticket {
 private Integer [] tickets=new Integer[]{80,35,41};

    public Integer[] getTickets() {
        return tickets;
    }

    public void setTickets(Integer[] tickets) {
        this.tickets = tickets;
    }

}

NumberGenerator:

public class NumberGenerator {
    private Integer [] numbers=new Integer[]{51,85,80,35,41};

    public Integer[] getNumbers() {
        return numbers;
    }

    public void setNumbers(Integer[] numbers) {
        this.numbers = numbers;
    }

}

TestClass To comparing:

for(int i=0;i<t.getTickets().length;i++)
        {
            for(int j=0;j<numberGenerator.getNumbers().length;j++)
            {
                if(t.getTickets()[i].equals(numberGenerator.getNumbers()[j]))
                {
                    System.out.println("Winner Number is::::"+t.getTickets()[i]);
                }
            }
        }

and if all the elements are same of two arrays then use this

boolean blnResult = Arrays.equals(t.getTickets(),numberGenerator.getNumbers());

Upvotes: 0

Guillaume
Guillaume

Reputation: 22822

Another question you should ask yourself, is where to do that comparison? If you "expose" the lucky numbers from the ticket to the rest of the world (using a public method), you may break encapsulation.

To keep it private and self-contained in Ticket, maybe you should have a method on your ticket, that goes like:

public boolean isWinningTicket(NumberGenerator numberGenerator) {
    // assuming both arrays are sorted
    return Arrays.equal(this.luckyNumbers, numberGenerator.getWinningNumbers());
}

Upvotes: 1

RokL
RokL

Reputation: 2812

You should use Arrays.sort to sort the arrays first, then comparing arrays is trivial with Arrays.equals.

Upvotes: 2

Hemant Metalia
Hemant Metalia

Reputation: 30668

comparing two arrays do not need to be in same class you can compare these using following method

boolean isEqual = Arrays.equals(array1(ticket class lucky numbers),array2(NumberGenerator winning numbers) );

Upvotes: 0

socha23
socha23

Reputation: 10239

if (Arrays.equals(aTicket.getNumbers(), aNumberGenerator.getNumbers())) {
    System.out.println("We have a winner!");
}

Upvotes: 0

Related Questions