Implement a vector that accepts anything

Asked

Viewed 87 times

2

I have to implement an array that is capable of storing objects of any kind. For example: V[3]= valor_int,valor_double,valor_float,valor_String. To do this I was thinking of creating a method that parses the values I want to insert, would be the best way out of this case?

  • vetor v = new Object[3]; or if you can use Collections: ArrayList list = new ArrayList<>();

  • You need to go into more detail to know.

  • @Diegof Thanks for the tip, I had not thought this way, I was going to create a parse method that was going to make the data conversion but this was going to run away from the proposed theme, Thank you I will try here.

  • @bigown The problem is this, I have to create an array that accepts any data I put can be a String,int and a float or String, Int, String, for example. The way I initially thought to solve the problem was to make a method that converted the variables, and my question was whether I had a better way to do it or could do it by parse.I don’t know if I explained it better?

  • No, you repeated what was already in the question. If you can convert, convert and do not worry about having to accept any type. If you can’t convert, this way doesn’t work and needs another, but you need to better understand the problem.

  • @Sorry Bigown, I’ll put the order of the exercise, all of a sudden it gets clearer. Exercise Order : Create an array, which is capable of storing objects of any type. My solution was to use parse, but I realized this would not meet the needs of the exercise.

  • Is this the whole statement of the exercise? What is in the question is only your assumption?

  • Yes the order of the exercise is just this: Create a vector, which is able to store objects of any type.

Show 3 more comments

1 answer

3


The solution is simpler than what is in the question, only by the comments can realize that it is only one array of objects. Then simply state that the type is Objeto:

Object[] array = new Object[5];

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

But note that the data will be stored in a boxed form. A int, and yes a Integer, Although the value is the same, the form is quite different and has important consequences. At the moment Java is like this and can not do more optimally.

  • Thanks, I’ll try to implement your answer too, I tried to vote her response as positive but still she gets Zero. Seeing your answer and the other colleague I see I have to learn a lot yet.

  • thanks for the attention!

Browser other questions tagged

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