Declare Setdouble - JAVA

4

I wanted to know how to declare a set with a generic type that is not a class. Example: Set<double> .

All the examples I've seen the set is of a class.

I'm starting to see now to see sets. I need to make a Set that has 20 random numbers and take a mean.

Will I have to create a class with double attribute to do this? Or is there another way?

    
asked by anonymous 27.08.2015 / 12:17

2 answers

3

The sets, which implement the interface Collection of Java , as ArrayList, LinkedList, HashSet, etc... do not accept primitive types.

But nothing prevents you from declaring a Set<Double> seuSet and then doing seuSet.add(2.33) , a primitive double. Java uses Wrappers or wrappers when this happens.

Every primitive type in java has a corresponding Wrapper :

int => Integer
long => Long
float => Float
double => Double
... assim por diante...

So when you try to add a primitive double to the array by doing seuSet.add(2.33) , Java actually executes the following: seuSet.add(new Double(2.33))

And for what you're wanting, which is to take an average of the numbers, I see no problem doing so.

    
27.08.2015 / 13:55
2

In fact, you can not use primitive types in Collections of Java.

If you want to work with double and Set , for your case, the alternatives are:

  • Use any library that provides collections implemented with primitive types, such as Trove or HPPC ;
  • Make your own implementation:);
  • Use Set<Double> same, if double primitive is not an obligation;
27.08.2015 / 13:09