diff --git a/src/main/java/com/github/hcsp/collection/Main.java b/src/main/java/com/github/hcsp/collection/Main.java index ae0f842..a7c0337 100644 --- a/src/main/java/com/github/hcsp/collection/Main.java +++ b/src/main/java/com/github/hcsp/collection/Main.java @@ -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 commonElementsIn(List a, List b) {} + public static Set commonElementsIn(List a, List b) { + ArrayList personsOne = new ArrayList<>(a); + ArrayList personsTwo = new ArrayList<>(b); + personsOne.retainAll(personsTwo); + return new HashSet<>(personsOne); + } // Person类,如果两个Person对象的name相等,则认为这两个对象相等。 public static class Person { @@ -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 list1 = Arrays.asList(new Person("张学友"), new Person("周杰伦")); List list2 = Arrays.asList(new Person("周润发"), new Person("周杰伦")); + System.out.println(list1); + System.out.println(list2); System.out.println(commonElementsIn(list1, list2)); } } diff --git a/src/test/java/com/github/hcsp/collection/MainTest.java b/src/test/java/com/github/hcsp/collection/MainTest.java index 1697f32..271fbf9 100644 --- a/src/test/java/com/github/hcsp/collection/MainTest.java +++ b/src/test/java/com/github/hcsp/collection/MainTest.java @@ -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; public class MainTest { @Test