0

Hay there, I need to create a list for a project with amount of terms for this method but it kind of didn't work as I thought. The "term"-names also have to look like this and have been sorted in the form of "Term:1", "Term:2",..., "Term:amount". If amount should be negative I have to return an empty list. I tried the following:

public static List <String> createTerms(int amount){
List <String> termNames = new ArrayList<String>();
    if (amount>0){
        termNames.add(amount,"Term:"+amount);
        Collections.sort(termNames);
        return termNames;
    }else
        return Collections.emptyList();
}

2 Answers 2

1

Even though this is tagged as JavaScript, this looks like Java. Take a look at the ArrayList documentation. Here is the method for add():

add(int index, E element)

Where it adds element to the structure at index. So it doesn't work the way you assumed in your code. If you would like to use ArrayList, even though I would advise against and suggest you use something like Map, found here, I would suggest you use a for-loop to add the terms in. So instead of:

 termNames.add(amount,"Term:");
 Collections.sort(termNames);

You can just do:

  if (amount > 0){
      for (int i = 0; i < amount; i++) {
          String element = "Term: " + (i + 1);
          termNames.add(element);
      } 
      return termNames;
  }

Also, I am a bit confused about your logic. Shouldn't the prompt be that you should return an empty list if amount < 0? Can you clarify a bit if my answer doesn't answer your question?

Sign up to request clarification or add additional context in comments.

2 Comments

Hello Sam, thank you very much for your answer! The prompt should return an empty list if the amount was < 0! I misstyped there (already edited it) Your answer did solve my question :) I am still not too fond of lists and maps, but I am really greatful for the answer. Especially the part with String element = "Term: " + (i + 1); So thanks again and have an especially nice day!
The if (amount > 0) check is unnecessary. Since the loop’s condition is i < amount and the initial value of i is zero, the desired behavior of producing an empty list for zero and negative amounts is already implied.
0

termNames will only ever have 1 element since the list is declared within the scope of the function. You should consider another data structure such as a dictionary for this implementation and make sure it's a global variable if you intend to fill it with more than 1 element

Edit: You should change to tag from Javascript to Java to ensure you receive correct advice

1 Comment

Thank you for the advice :) And I changed the tag

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.