List集合的几种创建方式

喜欢ヅ旅行 2023-06-13 08:56 77阅读 0赞
  1. package com.zsx.test;
  2. import com.google.common.collect.Lists;
  3. import org.junit.jupiter.api.DisplayName;
  4. import org.junit.jupiter.api.Test;
  5. import java.util.ArrayList;
  6. import java.util.Arrays;
  7. import java.util.List;
  8. import java.util.stream.Collectors;
  9. import java.util.stream.Stream;
  10. import static org.hamcrest.MatcherAssert.assertThat;
  11. import static org.hamcrest.Matchers.hasSize;
  12. /**
  13. * 测试背景:JDK13、Junit5、IDEA2019.2.3、guava
  14. */
  15. @DisplayName("Several ways to create a list")
  16. public class ListTest {
  17. @Test
  18. @DisplayName("Should contain six elements")
  19. void testCreat1() {
  20. var list = new ArrayList<>();
  21. list.add("one");
  22. list.add("two");
  23. list.add("three");
  24. list.add(null);
  25. list.add("");
  26. list.add(null);
  27. assertThat(list, hasSize(6));
  28. }
  29. @Test
  30. @DisplayName("Should contain six elements")
  31. void testCreat2() {
  32. var list = new ArrayList<>() {
  33. {
  34. add("one");
  35. add("two");
  36. add("three");
  37. add(null);
  38. add("");
  39. add(null);
  40. }
  41. };
  42. assertThat(list, hasSize(6));
  43. }
  44. @Test
  45. @DisplayName("Should contain six elements")
  46. void testCreat3() {
  47. var list = Arrays.asList("one", "two", "three", null, "", null);
  48. assertThat(list, hasSize(6));
  49. }
  50. @Test
  51. @DisplayName("Should contain six elements")
  52. void testCreat4() {
  53. var list = Stream.of("one", "two", "three", null, "", null).collect(Collectors.toList());
  54. assertThat(list, hasSize(6));
  55. }
  56. @Test
  57. @DisplayName("Should contain six elements")
  58. void testCreat5() {
  59. var list = Lists.newArrayList("one", "two", "three", null, "", null);
  60. assertThat(list, hasSize(6));
  61. }
  62. @Test
  63. @DisplayName("Should contain six elements")
  64. void testCreat6() {
  65. var list = List.of("one", "two", "three", "", "five", "six");
  66. try {
  67. // 不能有null值,java.lang.NullPointerException
  68. list = List.of("one", "two", "three", null, "");
  69. }catch (NullPointerException e) {
  70. e.printStackTrace();
  71. }
  72. assertThat(list, hasSize(6));
  73. }
  74. }

发表评论

表情:
评论列表 (有 0 条评论,77人围观)

还没有评论,来说两句吧...

相关阅读

    相关 JS 创建对象方式

     面向对象就是把属性和操作属性的方法放在一起作为一个相互依存的整体——对象,即拥有类的概念,基于类可以创建任意多个实例对象,一般具有封装、继承、多态的特性! ECMA-