ጃቫ ሁለት ዝርዝሮችን ያነፃፅሩ

በጃቫ ውስጥ ያለው የዝርዝር በይነገጽ ሁለት ዝርዝሮችን ለማነፃፀር እና ከዝርዝሮቹ ውስጥ የተለመዱ እና የጎደሉ ነገሮችን ለማግኘት የሚያስችሉ ዘዴዎችን ይሰጣል ፡፡



ለእኩልነት ሁለት ያልተነጣጠሉ ዝርዝሮችን ያወዳድሩ

ሁለት ዝርዝሮች እኩል መሆናቸውን ለማጣራት ከፈለጉ ፣ ማለትም አንድ አይነት እቃዎችን የያዙ እና በተመሳሳይ ኢንዴክስ ውስጥ የሚታዩ ከሆነ እኛ ልንጠቀምባቸው እንችላለን

import java.util.Arrays; import java.util.List; public class CompareTwoLists {
public static void main(String[] args) {
List listOne = Arrays.asList('a', 'b', 'c');
List listTwo = Arrays.asList('a', 'b', 'c');
List listThree = Arrays.asList('c', 'a', 'b');

boolean isEqual = listOne.equals(listTwo);
System.out.println(isEqual);

isEqual = listOne.equals(listThree);
System.out.println(isEqual);
} }

ውጤት


true false

equals() ን እንደሚመለከቱት ዘዴው እቃዎችን እና አካባቢያቸውን በዝርዝሩ ውስጥ ያወዳድራል።

ተዛማጅ:




ሁለት የተደረደሩ ዝርዝሮችን ያወዳድሩ

ሁለት ዝርዝሮች ተመሳሳይ እቃዎችን ይይዛሉ?



ቦታዎቻቸው ምንም ይሁን ምን ከእቃዎች አንጻር ብቻ ለእኩልነት ሁለት ዝርዝሮችን ለማነፃፀር የ | _ + + | | ን መጠቀም አለብን ዘዴ ከ sort() ክፍል

ለምሳሌ:

Collections()

ውጤት


import java.util.Arrays; import java.util.Collections; import java.util.List; public class CompareTwoLists {
public static void main(String[] args) {
List listOne = Arrays.asList('b', 'c', 'a');
List listTwo = Arrays.asList('a', 'c', 'b');
List listThree = Arrays.asList('c', 'a', 'b');

Collections.sort(listOne);
Collections.sort(listTwo);
Collections.sort(listThree);

boolean isEqual = listOne.equals(listTwo);
System.out.println(isEqual);

isEqual = listOne.equals(listThree);
System.out.println(isEqual);
} }


ሁለት ዝርዝሮችን ያወዳድሩ ፣ ልዩነቶችን ያግኙ

true true በይነገጽ በተጨማሪ በሁለት ዝርዝሮች መካከል ልዩነቶችን ለመፈለግ ዘዴዎችን ይሰጣል ፡፡

List ዘዴ ሁለት ዝርዝሮችን ያወዳድራል እና ሁሉንም የተለመዱ ንጥሎችን ያስወግዳል። የቀረው ተጨማሪ ወይም የጎደሉ ዕቃዎች ናቸው ፡፡

ለምሳሌ ሁለት ዝርዝሮችን ስናወዳድር | removeAll() እና listOne እና listTwo ምን ነገሮች እንደጎደሉ ለማወቅ እንፈልጋለን እንጠቀማለን

listTwo

ውጤት


import java.util.ArrayList; import java.util.Arrays; public class CompareTwoArrayLists {
public static void main(String[] args) {
ArrayList listOne = new ArrayList(Arrays.asList(1, 2, 3, 4, 5));

ArrayList listTwo = new ArrayList(Arrays.asList(1, 2, 4, 5, 6, 7));

listOne.removeAll(listTwo);

System.out.println('Missing items from listTwo ' + listOne);
} }

እንደዛው እኛ ከተጠቀምን

Missing items from listTwo [3]

እኛ እናገኛለን

listTwo.removeAll(listOne); System.out.println('Missing items from listOne ' + listTwo);

ሁለት ዝርዝሮችን ያነፃፅሩ ፣ የተለመዱ እቃዎችን ያግኙ

Missing items from listOne [6, 7] ዘዴው በሁለቱም ዝርዝሮች ውስጥ የተለመዱ ነገሮችን ብቻ ይጠብቃል ፡፡ ለምሳሌ:

retainAll()

ውጤት


public class CompareTwoArrayLists {
public static void main(String[] args) {
ArrayList listOne = new ArrayList(Arrays.asList(1, 2, 3, 4, 5));

ArrayList listTwo = new ArrayList(Arrays.asList(1, 2, 4, 5, 6, 7));

listOne.retainAll(listTwo);

System.out.println('Common items in both lists ' + listOne);
} }