Search code examples
javaarraysarraylistdeepequals

Comparing equals between 1D and 2D array in java


I have two questions: I am using JAVA programming language and I have found some difficulties using Arrays.

Here are some different arrays :

Object [] play1 = {0,3,6};
Object [] play2 = {0,3,6,4};
Object[][] pre = {{0,1,2},{0,3,6},{2,5,8},{6,7,8},{0,4,8},{2,4,6}};

Question 1 : Is it possible to check equals between play1 and pre using deepEquals? I also know that pre is 2D array and play1 is 1D array. If I want to check whether play1 is equal to pre, then I might check like:

if(Arrays.deepEquals(pre, play1)){
    System.out.print("true");
    }else{System.out.print("false");}

Is the code correct? Even though is is possible to check equals between 1D and 2D arrays? Or do I have to use ArrayList? I am not that much familiar with ArrayList. Would appreciate if anyone explain with example.

Question 2 : However, if I want to check between play1 and play2, then also the output is false. I want to check between two arrays even though they don't have equal element but if both array consists the same element such as: {0,3,6} can be found in both play1 and play2, then the output must come true..

Thanks.


Solution

  • For Question2:

    You can create List of objects and check as follows:

        List<Object> play1List = Arrays.asList(play1);
        List<Object> play2List = Arrays.asList(play2);
        if(play1List.containsAll(play2List) || play2List.containsAll(play1List))
            System.out.println("founD");
    

    For Question1:

        List<Object> play1List = Arrays.asList(play1);
        for (int i =0 ; i< pre.length;i++){
            List<Object> preList = Arrays.asList(pre[i]);
            if(preList.equals(play1List)){
                System.out.println("FounD"+preList);
                break;
            }    
        }