Object Arrangement in Java

0

Good morning, it turns out that I must make an arrangement that can store both data as int, String, boolean and in turn any other type of object that is entered. I was using the ArrayList since it gives the option to save whatever it is in each of its positions, but it turns out that I have to do it using a conventional arrangement, I just do not know what type to do it, if an int or a String. The fact is that you will have to do a casting but I do not know how to do it so that you will keep whatever is in your positions. Thank you very much:)

    
asked by José Ricaurte 07.02.2018 в 14:58
source

2 answers

1

What you are trying to do is a bit tedious since creating an Object type arrangement you can store all kinds of objects but when you retrieve those objects you will have to verify what type of object it is that you can be helpful. instanceof operator.

public class Main {

public static void main(String[] args) {
    Object[] arreglo = new Object[3];
    arreglo[0] = new Integer(12);
    arreglo[1] = "Cadena";
    arreglo[2] = new Double(78.3);

    for (Object object : arreglo) {
        if(object instanceof String) {
            System.out.println((String) object);
        }else if(object instanceof Integer){
            System.out.println(((Integer)object) + 12);
        }else if(object instanceof Double) {
            System.out.println(((Double)object) + 78.3);
        }
    }

}

}

I hope you find it useful.

    
answered by 07.02.2018 / 16:06
source
1

To store data you have so many classes in the Java.util library itself.

As you have already been told, you can use a Array of Object or for example, the most common data structures:

  • ArrayList<Object>
  • LinkedList<Object>
  • HashMap<K,Object>
  • TreeMap<K,Object>
  • Where 'K' is the type of key you want to use. Note that the value of each dictionary must be of type Object, any of primitive values are to be extensions of Object such as following :

    • int - > Integer
    • float - > Float
    • boolean -> Boolean
    • char - > Char

    The trouble with doing this is that when the stored data to get you to ask what type of object is using instanceOf() or getClass() . IT IS NOT RECOMMENDED TO DO THIS! Each object must be in its "drawer".

    "The socks go to the drawer of the socks"

        
    answered by 07.02.2018 в 15:31