0
class Employee
{
  int id;

  Employee(int id)
  {
    this.id = id;
  }

  public int getID()
  {   
    return id;
  }

  public void displayID()
  {
    System.out.println("ID="+id);
  }
}

public class Example
{
  public static void main(String[] args)
  {

    Employee employee1 = new Employee(100);
    Employee employee3 = null;

    List<Employee> arrayListEx = new ArrayList<Employee>();
    Set<Employee> setEx = new HashSet<Employee>();

    arrayListEx.add(employee1);
    arrayListEx.add(employee3);
    setEx.add(employee1);
    setEx.add(employee3);

  }
}

Friends, As per my understanding Set should not allow null values to get added to it. Should the above code snippet throw compile time error for "setEx.add(employee3)" ? Please advice, Thanks in advance.

Jagan
  • 37
  • 10
  • why don't you compile it and see ? there are online compilers in case you don't want to install one – niceman Jun 05 '17 at 18:32
  • I did that unfortunatley. In Runtime I got NullPointer but no compile time error. Then I thought of asking this question. – Jagan Jun 05 '17 at 18:42

1 Answers1

0

From the Java Hashset documentation: "This class permits the null element". The file will compile.

You mentioned you believe that Set doesn't allow nulls. This depends on its implementation (link to docs)

chakeda
  • 1,551
  • 1
  • 18
  • 40
  • Thanks Chakeda, This definately helps. If HashSet allows null values I am wondering what is the difference between an ArrayList & HashSet. Sorry if it seems like a basic question .... – Jagan Jun 05 '17 at 18:32
  • @Jagann you probably want to see this question : https://stackoverflow.com/questions/1035008/what-is-the-difference-between-set-and-list – niceman Jun 05 '17 at 18:35