1

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.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Tetsuo
  • 25
  • 7

4 Answers4

2

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
AxelH
  • 14,325
  • 2
  • 25
  • 55
2

What about stream and Optional

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

result type will be Optinal<Host>

Anton Balaniuc
  • 10,889
  • 1
  • 35
  • 53
  • Seems a bit complicate if OPs don't know how to compare a `String` but nice solution. Isn't there also a `findFirst` or something ? – AxelH Nov 17 '17 at 14:40
  • @AxelH, yes it might be a bit complicated. Yes, there is `findFirst` which will return exactly the fist element, `findAny` will return any element with match the condition. – Anton Balaniuc Nov 17 '17 at 14:50
1

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.

DevJava
  • 396
  • 1
  • 7
0

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;
  }
Yasin
  • 72
  • 7