Search code examples
javastaticarraylistthiscomparable

How do ArrayList, static, and this work in Java?


I was going through the article Java Sorting: Comparator vs Comparable Tutorial, and have some questions about it.

List<Employee> col = new ArrayList<Employee>();

col.add(new Employee(5, "Frank", 28));
col.add(new Employee(1, "Jorge", 19));
col.add(new Employee(6, "Bill", 34));
col.add(new Employee(3, "Michel", 10));
col.add(new Employee(7, "Simpson", 8));
col.add(new Employee(4, "Clerk", 16));
col.add(new Employee(8, "Lee", 40));
col.add(new Employee(2, "Mark", 30));

return col;
  1. This is an ArrayList of Employee objects. How many items can I add in this employee object? Can I do something like this?

    col.add(new Employee(5, "Frank", 28, "asas", "asas"));
    

    This is basically an array of Objects like Array[0] contains all these. And I am actually trying to access these array of Objects via ArrayList.

  2. Why is the printList made static? Can I also have other types here?

     private static void printList(List<Employee> list) {
         System.out.println("EmpId\tName\tAge");
         for (Employee e: list) {
             System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
         }
     }
    
  3. While comparing, what does this represent and o represent?

    public int compareTo(Employee o) {
         return this.empId - o.empId;
    }
    

    What does this mean here?


Solution

  • how many items can i add?

    You can add items to the list until the Java VM runs out of memory. There is no artificial limit.

    can i do something like this?

    col.add(new Employee(5, "Frank", 28, "asas", "asas"))
    

    No, because the Employee has no constructor which takes these arguments. But you can

    col.add(new Employee(5, "Frank", 28));
    

    This gives you two very similar but not identical instances in the list (they aren't identical because they are at different places in memory; they are similar because all fields have the same value).

    Why does the printList made static?

    So it can be called from the static method main() without creating an instance of TestEmployeeSort

    what does this represent and o represent?

    The sort algorithm will select two items in the list and call compareTo() on one with the other as argument. The former will be this, the latter will be in o.

    This way, the sort algorithm doesn't need to know much about the objects it compares.

    The advantage is that you can easily make objects comparable. The drawback is that the list must not contain null pointers or non-Employee instances.

    If that doesn't work for you, you can create a Comparator which also has a compareTo method but it takes two arguments.