Answer the question
In order to leave comments, you need to log in
Collection in Java - how to organize storage?
Hello! Please tell me how to store instances of different classes with different number of fields in a collection (for example, Vector)? And how to fully extract them from the collection so that you can safely access the fields?
For example, the collection class:
public class Numbers {
public static Vector<Object> coll = new Vector<Object>();
}
Answer the question
In order to leave comments, you need to log in
There is hardly any reason to store objects together that cannot have anything in common. For everything else, there are MasterCard interfaces and base classes.
Chai, back in Java 1.5, generics were invented in order not to use low-level things like Object, instanceof, etc.
PS And try to forget about Vector as soon as possible.
And store it like Object. Then to get and make type casting.
// Создание и заполнение коллекции
Vector<Object> coll = new Vector<Object>();
coll.add(new AnyTypeObject());
// Получаем объект
Object temp = coll.get(index);
// Делаем приведение типов
if(temp instanceof AnyTypeObject) {
AnyTypeObject obj = (AnyTypeObject) temp;
String myInformation = obj.getMyInformation();
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question