forStack
forStack

Reputation: 11

Object class of every type in Java

How can I create a class Object of any type ( string, char, int, float, double. short, long, byte,...) so that i can use a linkedlist list that accept everty type of the class Object

Upvotes: 1

Views: 86

Answers (3)

Lukas Eder
Lukas Eder

Reputation: 220762

If you want to store actual primitive values in a LinkedList, you may have to wait until Java 10, when project Valhalla might be implemented. You would then be able to instanciate new LinkedList<int>(), etc. Read the State of the Specialization document here:

For the time being, Trove4j is a Java project that implements specialised collections for primitive types, such as TIntList, for instance. Or you can put boxed types in your LinkedList, as others have mentioned.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

The class object that is compatible with anything in Java is Object.class. If you make a LinkedList<Object>, you would be able to put anything into it.

Note that primitive values, such as float, int, etc. would be stored in their object wrappers, i.e. Float, Integer, etc. This fact may be hidden by autoboxing, but generic Java collections cannot store primitives directly.

Upvotes: 2

roeygol
roeygol

Reputation: 5028

List<Object> ll = new LinkedList<Object>();
ll.add(new String("aaa"));
ll.add(new Integer(123));

Upvotes: 1

Related Questions