Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the differences between using <> and not using it in java? [duplicate]

Tags:

java

I have a piece of code like this:

@RequestMapping(value = "/find/{id}")
@GetMapping
public ResponseEntity<QuestionModel> find(@PathVariable("id") Long id) {
    Question question = questionService.find(id);
    QuestionModel questionModel = new QuestionModel(question);
    **return new ResponseEntity<>(questionModel, HttpStatus.OK);**
}

I wanna know that what's differences between that & this:

@RequestMapping(value = "/find/{id}")
@GetMapping
public ResponseEntity<QuestionModel> find(@PathVariable("id") Long id) {
    Question question = questionService.find(id);
    QuestionModel questionModel = new QuestionModel(question);
    **return new ResponseEntity(questionModel, HttpStatus.OK);**
}
like image 479
Arezoo Bagherzadi Avatar asked Sep 11 '26 06:09

Arezoo Bagherzadi


1 Answers

If you don't use any <...> you will use raw-types. You should never use raw-types, generics are way safer to use and prevent way more bugs due to increased compiler knowledge. Java only still supports it for backwards compatibility reasons < Java 5. See What is a raw type and why shouldn't we use it?

Using <> (diamond operator) instead of <Foo> (writing it out) is just syntactic sugar for convenience. The compiler replaces the diamond operator with the fully-written out type (same for var in Java 10). See What is the point of the diamond operator in Java 7?

// Are the same
List<Integer> values = new ArrayList<Integer>();
List<Integer> values = new ArrayList<>();

// Raw types, don't use if > Java 5
List values = new ArrayList();
// Assigning a raw-type to a generic variable, mixing both, don't use
List<Integer> values = new ArrayList();
like image 106
Zabuzard Avatar answered Sep 14 '26 04:09

Zabuzard