My controller class:
@PostMapping(value = "/uniqueUrl")
@ResponseBody
public ResponseEntity<MyResponse> urlGenerator(@RequestBody MyRequest myRequest){
log.info("Request for url : ", myRequest);
MyResponse myResponse= this.generateUrlService.urlGenerator(myRequest);
log.info("generateUniqueUrl response: ", myResponse.getLongUniqueUrlList());
return ResponseEntity.accepted().body(myResponse);
}
MyRequest class:
@Data
public class MyRequestimplements Serializable {
@NotNull(message = "Url cannot be null or empty")
private String url;
@NotNull(message = "count cannot be null or empty")
private int cound;
}
My service implemantation :
@Override
public myResponse urlGenerator(MyRequest myRequest) {
log.info("urlGenerator started..");
myUrlRequestValidator.validate(myRequest);
String longUrl = myRequest.getUrl();
int count = myRequest.getCount();
List<String> uniqueUrlList = Arrays.asList(new String[count]);
for (String string : uniqueUrlList) {
string = longUrl "/?";
for (int i = 0; i < rand.nextInt(11) 4; i ) {
string = letters.get(rand.nextInt(35));
}
uniqueUrlList.add(string);
log.info(string);
}
MyResponse response = new MyResponse();
response.setLongUniqueUrlList(uniqueUrlList);
return response;
}
MyResponse class:
@Data public class MyResponse extends BaseResponse {
private List<String> longUniqueUrlList;
private List<String> shortUrlList;
}
In the method where my Controller and Service class is as follows, the result of uniqueUrlList returns null. I want to add each string formed by the add method to the list, but it does not add it. Can you help me where am I going wrong?
CodePudding user response:
It is null because your List<String> uniqueUrlList
is initialized with Arrays.asList
which are fixed in size and unmodifiable, as specified in the Javadoc. The Arrays.asList(new String[count])
is also empty as there are no elements inside the new String[count]
.
Instead you should initialize it with a new ArrayList<String>()
:
List<String> uniqueUrlList = new ArrayList<String>();
Where you can then modify the list as you please, using a loop to add to your uniqueUrlList
as many as myRequest.getCount()
times.
CodePudding user response:
You should initialize a list by
List<String> uniqueUrlList = new ArrayList<>();