Simple way to compare 2 ArrayLists

后端 未结 10 1870
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 00:50

I have 2 arraylists of string object.

List sourceList = new ArrayList();
List destinationList = new ArrayList

        
10条回答
  •  广开言路
    2020-11-30 01:04

    If your requirement is to maintain the insertion order plus check the contents of the two arraylist then you should do following:

    List listOne = new ArrayList();
    List listTwo = new ArrayList();
    
    listOne.add("stack");
    listOne.add("overflow");
    
    listTwo.add("stack");
    listTwo.add("overflow");
    
    boolean result = Arrays.equals(listOne.toArray(),listTwo.toArray());
    

    This will return true.

    However, if you change the ordering for example:

    listOne.add("stack");
    listOne.add("overflow");
    
    listTwo.add("overflow");
    listTwo.add("stack");
    
    boolean result = Arrays.equals(listOne.toArray(),listTwo.toArray());
    

    will return false as ordering is different.

提交回复
热议问题