Declare Set<double> - JAVA

Asked

Viewed 220 times

4

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

All the examples I’ve seen set is from a class.

I’m starting to see sets now. I need to make a Set that has 20 random numbers and takes an average.

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

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 do seuSet.add(2.33), a primitive double. Java uses the Wrappers or wrappers when it happens.

Every primitive type in java has a Wrapper correspondent:

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 so seuSet.add(2.33) , actually Java runs 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 it that way.

2

In fact, you can’t use primitive types in Collections 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> even, if the double primitive is not a requirement;

Browser other questions tagged

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