Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 24 additions & 4 deletions src/main/java/com/github/hcsp/collection/Main.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
package com.github.hcsp.collection;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.*;

public class Main {
// 请编写一个方法,获得a和b集合中的公共元素。
public static Set<Person> commonElementsIn(List<Person> a, List<Person> b) {}
public static Set<Person> commonElementsIn(List<Person> a, List<Person> b) {
ArrayList<Person> personsOne = new ArrayList<>(a);
ArrayList<Person> personsTwo = new ArrayList<>(b);
personsOne.retainAll(personsTwo);
return new HashSet<>(personsOne);
}

// Person类,如果两个Person对象的name相等,则认为这两个对象相等。
public static class Person {
Expand All @@ -23,11 +26,28 @@ public String getName() {
public void setName(String name) {
this.name = name;
}

@Override
public boolean equals(Object obj) {
if(obj instanceof Person) {
Person person = (Person) obj;
return this.getName().equals(person.getName());
}
return false;
}


@Override
public int hashCode() {
return Objects.hash(name);
}
}

public static void main(String[] args) {
List<Person> list1 = Arrays.asList(new Person("张学友"), new Person("周杰伦"));
List<Person> list2 = Arrays.asList(new Person("周润发"), new Person("周杰伦"));
System.out.println(list1);
System.out.println(list2);
System.out.println(commonElementsIn(list1, list2));
}
}
5 changes: 3 additions & 2 deletions src/test/java/com/github/hcsp/collection/MainTest.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package com.github.hcsp.collection;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

为什么要修改测试???

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

不知道,它自动改的


public class MainTest {
@Test
Expand Down