Comparing arrays that have same elements in different order

前端 未结 6 950
遥遥无期
遥遥无期 2020-12-17 21:26

I wrote below code to compare to arrays that have same elements but in diff order.

 Integer arr1[] = {1,4,6,7,2};
 Integer arr2[] = {1,2,7,4,6};
6条回答
  •  借酒劲吻你
    2020-12-17 21:38

    Try this function it return array:-

    public static String[] numSame (String[] list1, String[] list2) 
         {  
              int same = 0;  
              for (int i = 0; i <= list1.length-1; i++) 
              {  
                 for(int j = 0; j <= list2.length-1; j++) 
                 {  
                    if (list1[i].equals(list2[j])) 
                    {  
                        same++;  
                        break;  
                    }  
                 }  
              }  
    
              String [] array=new String[same];
              int p=0;
              for (int i = 0; i <= list1.length-1; i++) 
              {  
                 for(int j = 0; j <= list2.length-1; j++) 
                 {  
                    if (list1[i].equals(list2[j])) 
                    {  
                        array[p]=  list1[i]+"";
                        System.out.println("array[p] => "+array[p]);
                        p++;
                        break;  
                    }  
                 }  
              } 
              return array;
           }  
    

提交回复
热议问题