JHipster生成代码 - LinkedList vs List

时间:2015-05-18 15:45:32

标签: java jhipster

我想知道为什么选择在生成的AccountResource.getAccount()代码中使用LinkedList?

/**
 * GET  /account -> get the current user.
 */
@RequestMapping(value = "/account",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<UserDTO> getAccount() {
    return Optional.ofNullable(userService.getUserWithAuthorities())
        .map(user -> {
            return new ResponseEntity<>(
                new UserDTO(
                    user.getLogin(),
                    null,
                    user.getFirstName(),
                    user.getLastName(),
                    user.getEmail(),
                    user.getLangKey(),
                    user.getAuthorities().stream().map(Authority::getName).collect(Collectors.toCollection(LinkedList::new))),
                HttpStatus.OK);
        })
        .orElse(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
}

UserDTO构造函数中的最后一个参数&#34; roles&#34;,一个字符串列表。这是从用户记录的权限集(HashSet)中提取出来的。不确定为什么使用LinkedList而不仅仅是列表,例如:

...
user.getAuthorities().stream().map(Authority::getName).collect(Collectors.toList())),
...

很抱歉,如果我遗漏了一些明显的东西。我刚刚过渡到Java 8,我的Lambda知识远未完成。

2 个答案:

答案 0 :(得分:0)

它是开源的,所以让我们看一下源代码,做一个责备,我们找到:https://github.com/jhipster/generator-jhipster/commit/63a02d6e711c535f92821479c83c695cd1c340d6。显然只是为了删除IDEA中的警告。

答案 1 :(得分:0)

使用Collectors.toList(),您无法指定实现类。

javadoc:

  

返回一个将输入元素累积为新元素的收集器   名单。不保证类型,可变性,   返回List的可序列化或线程安全性;如果更多   需要控制返回的List,使用   toCollection(供应商)。

LinkedList非常适合只有几个项目的简短列表。这似乎非常适合您可能只有一个项目的当局。例如,ArrayList将分配一个数组。