krltos
krltos

Reputation: 335

returning the ArrayList cast to List vs no casting

What is the difference, if any, between the two:

@ModelAttribute(value = "attendanceStatuses")
public List<Code> getAttendanceStatusCodes() {
    List<Code> attendanceStatuses= new ArrayList<Code>(
      cacheService.getValidCodesOfCodeGroup(CODE_GROUP));
    return attendanceStatuses;
}

and

@ModelAttribute(value = "attendanceStatuses")
public List<Code> getAttendanceStatusCodes() {
    return cacheService.getValidCodesOfCodeGroup(CODE_GROUP);
}

The cacheService method is:

List<Code> getValidCodesOfCodeGroup(CodeGroupName codeGroupName);

Upvotes: 0

Views: 45

Answers (1)

Eran
Eran

Reputation: 394156

The first snippet returns a copy of the List returned by cacheService.getValidCodesOfCodeGroup(CODE_GROUP):

new ArrayList<Code>(cacheService.getValidCodesOfCodeGroup(CODE_GROUP))

The second snippet does not - it simply returns cacheService.getValidCodesOfCodeGroup(CODE_GROUP).

There is no casting in any of these snippets though.

Note that assigning the List to a local variable before returning it makes no difference. You can change the first snippet to:

public List<Code> getAttendanceStatusCodes() {
    return new ArrayList<Code>(cacheService.getValidCodesOfCodeGroup(CODE_GROUP));
}

without changing the behavior.

Upvotes: 3

Related Questions