Is it possible to set several object to List?
If I declare List<Object>
it will accept any kind of objects.
If I declare List<Integer>
it will accept only integers.
Can I make a list which will accept Integers
OR Floats
and nothing else?
Asked
Active
Viewed 77 times
0

Jason Aller
- 3,541
- 28
- 38
- 38

Yarh
- 4,459
- 5
- 45
- 95
3 Answers
1
Is it possible to set several object to List?
Yes you can do that by declaring list as List<Object>
Can i make a list wich will accept Integers OR Floats and nothing else?
There is no direct way to accept only two type.
Possible ways of doing it is
1) Take individual lists (preferred)
2) Take List of type Object. And use
insatanceof
key words while using it.- 3) Implementing your own list and override
add()
method. While adding to that list check type of instance and if it is not desired, throwException
.

Suresh Atta
- 120,458
- 37
- 198
- 307
-
+1 I think `List – akash Jul 03 '14 at 11:35
-
@TAsk I won't mess up. Will use individual lists :) – Suresh Atta Jul 03 '14 at 11:36
-
Well Same here but still it's an option isn't it? – akash Jul 03 '14 at 11:37
-
1Yes we can do that and have to use [instanceof](http://www.javapractices.com/topic/TopicAction.do?Id=31) while retrieving from list :). And the link says `"Anytime you find yourself writing code of the form "if the object is of type T1, then do something, but if it's of type T2, then do something else," slap yourself.` – Suresh Atta Jul 03 '14 at 11:40
-
@sᴜʀᴇsʜᴀᴛᴛᴀ but sometimes you dint know which object will come. I met server which returned json object if there were only one element and json array when it gave more then one element. – Yarh Jul 03 '14 at 11:47
0
You can get a support from This tutorial, And you can read the java documentation as well.
There is a thread also here.

Community
- 1
- 1

user3717646
- 436
- 3
- 10
0
To simulate a list which can hold integer or float values I would probably use an "Either" type. While java doesn't provide it automatically, stackoverflow can help with a good enough implementation:
How can I simulate Haskell's "Either a b" in Java
so you would have:
List<Either<Integer,Float>> list;