Tetsuo
Tetsuo

Reputation: 25

How can I return an object from a ArrayList?

I would like to return the Host thats have the same domain as the Host in the List. But it gives me and error: "This method have to return a type of Host".

How I have to return the object Host?

public class Manager {

private List<Host> hosts = new ArrayList<Host>();

public Host getHost (String domain) {

      for(int i = 0; i < hosts.size(); i++) {
          if(domain == hosts.get(i).getDomain()) {
              return hosts.get(i);
          }}      
  }

Thanks.

Upvotes: 1

Views: 97

Answers (4)

DevJava
DevJava

Reputation: 396

You just need to return null after your loop.

  public Host getHost (String domain) {
        for(int i = 0; i < hosts.size(); i++) {
            if(domain.equals(hosts.get(i).getDomain())) {
              return hosts.get(i);
            }
        }      
        return null;
    }

You can also throw an Exception if nothing found.

Upvotes: 1

Yasin
Yasin

Reputation: 72

Could it be because the last line in your method is not a return? Maybe try this:

public Host getHost (String domain) {
      Host host = null;
      for(int i = 0; i < hosts.size(); i++) {
          if(domain.equals(hosts.get(i).getDomain())) {
              //saves in the variable declared outside of for
              host = hosts.get(i);
          }
      }
      //attention: if nothing is found in your arraylist, the returned object is refers to null
      return host;
  }

Upvotes: 0

Anton Balaniuc
Anton Balaniuc

Reputation: 11739

What about stream and Optional

return hosts.stream().filter(host -> host.getDomain().equals(domain)).findAny();

result type will be Optinal<Host>

Upvotes: 2

AxelH
AxelH

Reputation: 14572

First, to compare String you need to use String.equals

if(domain.equals(hosts.get(i).getDomain()))

Second, you don't return something if this is not found, you need to either return null or throw an exception

 for(int i = 0; i < hosts.size(); i++) {
     ...
 }
 return null;

or

 for(int i = 0; i < hosts.size(); i++) {
     ...
 }
 throw new ItemNotFoundException(); //Or any exception you want

Upvotes: 2

Related Questions