0

Suppose that there is a method called Person.

class Person {
    int id;
    String name;
    String number;

    constructor with that values, and getter/setter methods
}

and a method with a return type of String[]

class Test{
    
    List<Person> list = new ArrayList<>;

    String[] getValues(int personID) {
        for(Person person : list) {
            if(person.getId() == personID) {
                
            }
        }
    }
}

As you can see that if person.getId() is equal to the parameter, "personID", how do we return the values of that matching person in the form of: [name, number] when the return type of that method is String[]?

For example:

main_method() {
    (suppose that there are some Persons added to that list through Test test.addList() method)
    System.out.println(test.getValues(2));
}

console :
    [Tom, 1234]

Thanks in advance!

yoo seung
  • 23
  • 2
  • 1
    Create an array; put the matching elements in the array; return the array. Alternatively, use a list. – khelwood Apr 24 '21 at 12:33
  • 1
    `return new String[]{person.getName(), person.getId()};` but using an array for this is bad design. The caller just has to know that element 0 = name, element 1 = id. What if the caller gets an array without 2 elements? What if there are more or less? Just return the `Person`, and let the caller decide what values they want from it. – Michael Apr 24 '21 at 12:35
  • @khelwood then I need to change the return type for that method to array? I need to retain the return type of String[] for that method... – yoo seung Apr 24 '21 at 12:46
  • `String[]` is an array – khelwood Apr 24 '21 at 13:06
  • @khelwood Then when I do System.out.println(getValues(1), wouldn't it print like [address, address], not the actual values of [name, number]? – yoo seung Apr 24 '21 at 13:17
  • Then you can check out [What's the simplest way to print a Java array?](https://stackoverflow.com/q/409784/3890632) – khelwood Apr 24 '21 at 14:09

0 Answers0