본문 바로가기

JavaScript/공부공부

[JS] 배열값 비교 (include, '===') / Java_List 비교

 

* 배열요소 비교 ( include ) 

const arr = [1, 2, 3, 4, 5];

console.log(arr.includes(2)); // true

 

* includes() 함수는 내부적으로 '===' 연산자를 사용하여 요소를 비교하기 때문에 다른 타입은 비교 불가능.

const mixedArr = [1, "2", 3];

console.log(mixedArr.includes(2)); // false
console.log(mixedArr.includes("2")); // true

 

배열을 해체해서 비교해줘야 한다.

const num = 2;
const exists = mixedArr.some(value => value.toString() === num.toString());

console.log(exists); // true

=> 배열요소와 찾는 숫자를 모두 문자열로 변경 후 비교.

 


 

* 객체배열 비교

const people = [
    { id: 'first', name: 'one' },
    { id: 'second', name: 'two' },
    { id: 'third', name: 'three' },
    { id: 'fourth', name: 'four' },
    { id: 'fifth', name: 'five' }
];

const SomePeople = [
    { id: 'first', name: 'one' },
    { id: 'fourth', name: 'four' },
    { id: 'fifth', name: 'five' }
];

const SomePeopleCopy = [
    { id: 'first', name: 'one' },
    { id: 'fourth', name: 'four' },
    { id: 'fifth', name: 'five' }
];

const anotherCopy = SomePeople;

 

각 배열들을 비교해보면 ( '===' )

console.log(SomePeople === SomePeopleCopy) // false
console.log(SomePeople === anotherCopy) // true

=> SomePeople 과 SomePeopleCopy 는 내용은 같지만 메모리 주소가 다른 별개의 객체이기 때문에 false

=> SomePeople 과 anotherCopy는 같은 메모리 주소를 참조하는 객체이기 때문에 때문에 true

 


 

people에서 SomePeople 의 요소들을 제거해보자.

const remainingPeople = people.filter(item =>
    !SomePeople.some(val => val.id === item.id)
);

console.log(remainingPeople)
// [ {id: 'second', name: 'two'}, {id: 'third', name: 'three'} ]

 


 

* 자바에서의 비교 * 

문자열비교 (String)

String str1 = "hello";
String str2 = "hello";
String str3 = new String("hello");

boolean result1 = str1.equals(str2); // true, 같은 내용
boolean result2 = str1.equals(str3); // true, 같은 내용

boolean result3 = str1 == str2; // true, 같은 객체를 참조 (리터럴 풀)
boolean result4 = str1 == str3; // false, 다른 객체를 참조

 


 

[ 리스트 비교 (ArrayList) ]

 

-  List<String> 인 경우

 

List.equals() 메소드 

 1. 객체동일성(메모리주소) 비교 ( '==' ) => 같다면 true

 2. 타입 비교 ( List 인터페이스 구현 )

 3. 리스트의 크기 비교 => 다르다면 false

 4. 요소별 비교 : 각 요소를 equals() 메소드로 순서대로 비교.

  => 모든 요소가 같다면 true, 하나라도 다르다면 false

 

List<String> list1 = Arrays.asList("apple", "banana", "cherry");
List<String> list2 = Arrays.asList("apple", "banana", "cherry");
List<String> list3 = Arrays.asList("banana", "apple", "cherry");

System.out.println(list1.equals(list2));  // true, 같은 요소, 같은 순서
System.out.println(list1.equals(list3));  // false, 같은 요소, 다른 순서

 


remove( Object o ) 메소드

1. 리스트 순회 &  동등성 검사 : 객체 'o'와 각 리스트의 요소를 equals() 메소드로 비교.

2. equlas() 의 반환값이 true라면 리스트에서 해당 요소 제거.

3. 요소가 제거되면 remove() 는 true 반환 / 리스트에 해당 요소가 없다면 false 반환.  

 

List<String> fruits = new ArrayList<>(Arrays.asList("apple", "banana", "cherry", "banana"));
boolean isRemoved = fruits.remove("banana");  // "banana" 요소를 제거합니다.

System.out.println(isRemoved);  // true
System.out.println(fruits);     // ["apple", "cherry", "banana"]

=> 첫번째로 발견된 요소만 제거하기 때문에 뒤에 동일한 요소가 있다면 그대로 남아있음.

 


 

-  List<Map<String, Object>> 인 경우

=> 이 때 List의 비교는 좀 더 세세한 비교가 필요.

 

첫번째 리스트 'people'

List<Map<String, Object>> people = new ArrayList<>();
 
System.out.println("Initial People list:");
for (Map<String, Object> person : people) {
    System.out.println(person);
}


// 출력결과
Initial People list:
{id=first, name=one}
{id=second, name=two}
{id=third, name=three}
{id=fourth, name=four}
{id=fifth, name=five}

 

두번째 리스트 'SomePeople'

List<Map<String, Object>> SomePeople = new ArrayList<>();

System.out.println("Some People list:");
for (Map<String, Object> person : somePeople) {
    System.out.println(person);
}

// 출력결과
Some People list:
{id=first, name=one}
{id=fourth, name=four}
{id=fifth, name=five}

 

* 주의 *

people에서 SomePeople 의 요소들을 제거해보자.

people.removeAll(somePeople);

System.out.println("People after removal:");
for (Map<String, Object> person : people) {
    System.out.println(person);
}


// 출력결과
People after removal:
{id=first, name=one}
{id=second, name=two}
{id=third, name=three}
{id=fourth, name=four}
{id=fifth, name=five}

removeAll 은 equals() 메소드에 의존하기 때문에 동등성 평가가 제대로 이루어지지 않을 수 있다.