Object Array (not objects) in Java - How to use

Asked

Viewed 147 times

2

Hello, I have the following task to do:

I have three types of employees (Commissioned, Salaried and Hourly) and I have to add them to a list (ArrayList) to manage them.

ArrayList<Commissioned> c = new ArrayList<>();
ArrayList<Hourly> h = new ArrayList<>();
ArrayList<Salaried> s = new ArrayList<>();

I need them all to be in a single Array. I could create a Employees interface, implement Employees in each of the classes and make a

ArrayList<Employees> employees = new ArrayList<>();

but that’s not what I need.

What I have to do is

ArrayList<Objects> employees = new ArrayList<>();

But I don’t know how to work with these employees in an Array of Objects. How to use things like instanceof or casting of objects.

What I wish I could do:

Find out if an item of this ArrayList is an instance of the class Commissioned, Salaried or Hourly. And how to use the methods of each of the array items, since the methods of each class are different.

Note: If you want to see how the project is currently being implemented: https://github.com/WilliamPhilippe/Projeto-de-Software/tree/master/FolhadePagamentos/src/com/company

  • This in the Working Line 11 class

Obs2: I searched a lot on the Internet, but I couldn’t find things about Objects Array, just about Objects Array.

2 answers

5

I created three classes:

  • Commissioned,
  • Hourly
  • Salaried.

To simplify the example I added only one field to each class:

  • Commissioned.name,
  • Hourly.age
  • Salaried.salary.

I copied the ArrayList c, h and s of your question and populated them with an object each.

I created the ArrayList<Object> employees and populated it with c, h and s.

I didn’t use ArrayList<Objects> as in the question why Objects is a utility class consisting of static methods for operating on objects.

Then for each object in employees I took your class with the method getClass() and compared it with one of the classes Commissioned, Hourly and Salaried. In case the comparison is successful I made the caste conversion of Objectfor the compared type and assigns a value to the intrinsic property for each class.

I repeated the same process only instead of assigning I printed the value already assigned to each type.

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {

        //Copiei da pergunta
        ArrayList<Commissioned> c = new ArrayList<>();
        ArrayList<Hourly> h = new ArrayList<>();
        ArrayList<Salaried> s = new ArrayList<>();

        //Popula cada ArrayList com um objeto
        c.add(new Commissioned());
        h.add(new Hourly());
        s.add(new Salaried());

        //Cria um ArrayList<Object>
        ArrayList<Object> employees = new ArrayList<>();

        //Passa "c", "h" e "s"  para employees 
        employees.addAll(c);
        employees.addAll(h);
        employees.addAll(s);

        //itera sobre employees
        for(Object employ : employees){
          //Faz a comparação do objeto com a classe
          if (employ.getClass() == Commissioned.class){

            //Faz a conversão de casta para o tipo adequado e atribui valor
            ((Commissioned)employ).name = "João";

          } else 
          if (employ.getClass() == Hourly.class){
            ((Hourly)employ).age = 30;
          } else
          if (employ.getClass() == Salaried.class){
            ((Salaried)employ).salary = 500.50f;
          } else throw new Exception("Objeto desconhecido");
        }

        for(Object employ : employees){
          if (employ.getClass() == Commissioned.class){
            System.out.println("Commissioned name:" + ((Commissioned)employ).name);
          } else 
          if (employ.getClass() == Hourly.class){
            System.out.println("Hourly age:" + ((Hourly)employ).age);
          } else
          if (employ.getClass() == Salaried.class){
            System.out.println("Salaried salary:" + ((Salaried)employ).salary);
          } else throw new Exception("Objeto desconhecido");
        }


    }
}

//Declaração hipotética de classes
class Commissioned{
    String name;    
}

class Hourly{   
    int age;    
}

class Salaried{ 
    float salary;   
}

Code in the Repl.it

  • 1

    If I need to add a new employee in "Employees" I can do Employees.add(newEmployee) or I have to add in "c" or "h" or "s" before?

  • It is not required. In fact you can delete "c", "h" and "s" and stay only with Employees. I used them to follow the reasoning of the question.

  • 1

    Is there a specific reason to use employ.getClass() == X.class instead of employ instanceof X?

  • @Douglas I used on account of the ease of reading code. Personally I prefer the use of instanceof.

0

Following your logic, you could do so:

ArrayList<Commissioned> c = new ArrayList<>();
ArrayList<Hourly> h = new ArrayList<>();
ArrayList<Salaried> s = new ArrayList<>();

ArrayList<Object> employees = new ArrayList<>();

//Atribuição das classes a ArrayObject, e o que mais você quiser, String, Long, etc;
employees.add("Minhas classes!");
employees.add(c);
employees.add(h);
employees.add(s);

//Agora a leitura das classes, vou criar uma fun para setar os dados;
public void setItemViewType(ArrayList<Object> employees) {
    for(int position=0; position<itensMeusDados.size(); position++){
        if (employees.get(position) instanceof Commissioned) {
            ArrayList<Commissioned> c2= (Commissioned) employees.get(position);
        } else if (employeesTeste.get(position) instanceof Hourly) {
            ArrayList<Hourly> h2= (Hourly) employees.get(position);
        } else if (employees.get(position) instanceof Salaried){
            ArrayList<Salaried> s2= (Salaried) employees.get(position);
        } else if (employees.get(position) instanceof String){
            String titulo = (String) employees.get(position);
        }
    }
}

setItemViewType(employees);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.