Using Generic Primitive Arrays in Scala [duplicate] - java

This question already has answers here:
How can I use primitives in Scala?
(2 answers)
Closed 7 years ago.
I recently asked this question about whether it was possible to parameterize the type of a primitive array in Java. (Basically, I have an array that I want to be either a double[] or a float[] based on some argument. I'm using arrays of primitives rather than arrays of wrapper classes (Double[], Float[]) because they're much more memory-and-time efficient, especially when dealing with big vector operations. The answer, it appears, is No, you can't do that in Java.
So, my new question is: Can I do this in Scala? I understand that primitives are kind of more hidden, and only boxed on certain operations... So if it is possible to parameterize my arrays as being of Double or Float, and the compiler does implement them as primitives, how do I tell if they're being unboxed, or otherwise implemented less efficiently than if I were to just go "Find: Double, Replace: Float" in my source code?

Does this work for you?
object SpecialisedArray {
def apply[#specialized(Float, Double) T: ClassTag](size: Int) = new Array[T](size)
}

Related

Is it a better practice to use Reference types or primitive types in Java? [duplicate]

This question already has answers here:
When to use wrapper class and primitive type
(11 answers)
Closed 6 years ago.
Is it considered a better practice to use and manipulate Reference types instead of primitive types in Java ?
We often see java programs mixing both of them, is it better to use only primitive types or only reference types ? Or mix them according to the needs and what are the criteria to choose between a primitive or reference type ?
Thanks
Assuming you mean primitive wrapper types (Integer, Boolean, etc.) and not reference types in general: when you have a choice (often you don't: e.g. you are using API which requires one or the other, or you use them as generic type arguments, or you want to be nullable), prefer primitive types, because on the whole this will make your code simpler and faster.
Be careful if you need to switch from one to another, because == will still compile but give different results... usually.
One important criteria is the question: Can it be null?
For example think of an id in an database-entity and ask yourself if there is a time where the id can be null.
You can choose primitive type for non-null-Values.

Is it better to create a string in Java as an object or as a primitive type? [duplicate]

This question already has answers here:
Strings are objects in Java, so why don't we use 'new' to create them?
(15 answers)
Closed 7 years ago.
My understanding of strings in Java is that they can be either primitive types or objects. When creating strings is it better to create them as objects with the new command and a constructor or as a primitive type similar to int?
My understanding of strings in Java is that they can be either primitive types or objects
Wrong. Strings are always objects. Its just that String literals ("someStringHere") are treated in a special manner by the compiler and then interned by the JVM.
If your question is whether -
String s = "Abc";
is better than
String s = new String("Abc");,
Yes, since the second one is redundant and creates 2 Strings (one in constants pool and another on heap).

Why Wrapper Class Concept came in Java? [duplicate]

This question already has answers here:
Why are there wrapper classes in Java? [duplicate]
(9 answers)
Closed 7 years ago.
I know what a wrapper class is, they wrap primitive types (e.g. int, double, etc) to objects of their respective class.
But I want to know with a Java Code Example which can explain me practically.
With wrapper class and with out wrapper class what it will do.
When the Java language was "invented" people thought that having primitive types int, long, ... would avoid performance issues. 15+ years back, there were no efficient JIT compilers; so it made a huge difference if you had to create an array for 10000 ints ... or for 10 000 Integer objects.
On the other hand, Java wants to be a object-oriented language. Therefore those primitive types came with accompanying classes. You are correct in the sense: if there would be no primitive tpyes, just Integer, Long, ... and so on, the Java type system would be more consistent, much simpler ... but back in 1997 this simple type system would have been to "expensive" regarding performance. And unfortunately people didn't think about allowing primitive types in bytecode ... but not having them in the Java language itself (and the compiler converting Integer to int internally).
The main usage nowadays is the fact that the Java compiler does autoboxing (automated conversion between primitive and "object based" types); so you can write stuff like:
Map<Integer, String> someMap = ...
someMap.put(5, "string")
A simple one line answer could be that you can have ArrayList<Integer> but you can not an ArrayList<int>. They are used for collections, polymorphism etc. So I think Java designers wanted to make things simple and thats why they used the concept of wrapper class.
Java is an object-oriented language and as said everything in java is
an object. But what about the primitives? They are sort of left out in
the world of objects, that is, they cannot participate in the object
activities, such as being returned from a method as an object, and
being added to a Collection of objects, etc. . As a solution to this
problem, Java allows you to include the primitives in the family of
objects by using what are called wrapper classes.
Wrapper classes are used to convert any data type into an object. The primitive data types are not objects; they do not belong to any class; they are defined in the language itself. Sometimes, it is required to convert data types into objects in Java language
What is a Wrapper class?
A wrapper class wraps or encloses a data type and gives it an appearance of an object. You can also get the primitive datatype from the object.
Observe the following example.
int x = 100;
Integer iObj = new Integer(x);
The int data type (x) is converted into an object (iObj) with the help of an Integer class. This can be used whever an object is required.
The following code can be used to unwrap the object iObj and obtain the primitive datatype.
int y = iObj.intValue();
System.out.println(y); // prints 100
intValue() is a method of Integer class that returns an int data type.
Why Wrapper classes?
To convert primitive data types into objects and vice versa.
Wrapper types exists in Java primarily for two reasons:
to allow type conversion in an object-oriented fashion
all Collection types used generic java Objects, so if you need a List of, say floating point numbers, you can't use simple float numbers, because they are not objects. Also, they don't inherit from java.lang.Object
So you can have an ArrayList<Integer> because Integer extends from Object (as every other object inside the JVM). But you can't have an ArrayList because int is not an object type: it's just a simple int variable, without methods, instance variables, etc.
Since Java 1.5 you have automatic boxing and unboxing of primitive types into their correspondent wrapper types, which makes everything a little bit more confusing. Consider this listing:
List list = new ArrayList<Integer>()
list.add(new Integer(10))
list.add(20)
Here you see that this list only uses Integer objects. In the last line the compiler is putting the simple value 20 inside a new Integer object to save you some typing. This is a little syntax sugar but the idea remains: list can only use Integer objects.

Primitive vs Object type in Java [duplicate]

This question already has answers here:
Why do people still use primitive types in Java?
(21 answers)
Closed 9 years ago.
This question came to my mind because I have read somewhere that Java is not a pure Object oriented language since it is using primitives (which are not objects). I can agree with that. Now my problem is why we are using primitives/wrappers while we already have Object in same type?
As an example if we consider Integer, It has same value limit as int other than object behavior. why still Java use primitives under these condition?
As my opinion, if Java only use Object type Autoboxing and Unboxing no need. Also there is no primitive for String by the way.
One reason is due to memory usage. Primitives, such as int, float etc. require less memory allocations (I think 4 bytes) in comparison to Objects which are at the very least 8 bytes. Please see the following reference:
In addition, a lot of arithmetic (numeric) is completed with the use of primitives rather than their Object equivalents and this is another reason why they are quite critical in the Java language.

Java collections. Why no Primitive Types? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
storing primitive values in a java collection?
My Java textbook says elements of a collection, for example ArrayList, cannot be primitive types. Is there a reason for this? I mean did someone at Sun decide on this or is there some barrier against doing it? I understand my example half-answers my question since ArrayList requires an object and primitives are not objects. But then I think why can't they have primitive types as well?
is there some barrier against doing
it?
You could write near-identical versions of ArrayList that were tailor made to store one of the non-class types, e.g. IntegerArrayList and so on. The barrier against this is that there would be an explosion of such classes, as you'd multiply the number of primitive types by the number of collection types. In order to keep the standard collection framework manageable, this was ruled out.
To solve this more neatly in the language, you'd need generics to allow primitive types to serve as type parameters, and improve the interaction between arrays and generics.
Storing unwrapped primitives would dramatically complicate the collections code. Whereas, with the wrappers (Integer for int, etc.), the code is fairly straight-forward. For several years now, Java has supported "auto-boxing", which means that if you give an int where an Integer is expected, the int is wrapped up in an Integer instance for you (and vice-versa).
There are objects called "wrappers" that represent all of the primitive types. For example, there is a class called Integer that supports int. You can use the primitive wrappers to hold values in a Collection.
The problem with primitive types (at least until Java 5) is that they didn't extend from the base Object class. All of the collections need to specify a class for all the methods they are using - and they specify Object, since Object is the base of all the classes.
As of Java 5, you will find that Java will implicitly switch between a primitive and it's corresponding wrapper class when you need it. This means you can add an int, or a double, etc. to a Collection. The VM will automatically wrap the primitive in a wrapper class for you and place the wrapper in the Collection.
Currently the only way to store primtives directly into a collection, is to have a collection for each primitive type e.g. TIntArrayList.
You are likely to find that even though ArrayList is slower than using primitives, it is fast enough for 90+% of use cases.
Read this article on wikipedia. It might help: http://en.wikipedia.org/wiki/Object_type_(object-oriented_programming)#Autoboxing
In computer science, an object type
(a.k.a. wrapping object) is a datatype
which is used in object-oriented
programming to wrap a non-object type
to make it look like a dynamic object.
Some object-oriented programming
languages make a distinction between
reference and value types, often
referred to as objects and non-objects
on platforms where complex value types
don't exist, for reasons such as
runtime efficiency and syntax or
semantic issues. For example, Java has
primitive wrapper classes
corresponding to each primitive type:
Integer and int, Character and char,
Float and float, etc. Languages like
C++ have little or no notion of
reference type; thus, the use of
object type is of little interest.
Boxing is the process of placing a
primitive type within an object so
that the primitive can be used as a
reference object. For example, lists
may have certain methods which arrays
might not, but the list might also
require that all of its members be
dynamic objects. In this case, the
added functionality of the list might
be unavailable to a simple array of
numbers. For a more concrete example,
in Java, a LinkedList can change its
size, but an array must have a fixed
size. One might desire to have a
LinkedList of ints, but the LinkedList
class only lists references to dynamic
objects — it cannot list primitive
types, which are value types.
To circumvent this, ints can be boxed
into Integers, which are dynamic
objects, and then added to a
LinkedList of Integers. (Using generic
parameterized types introduced in J2SE
5.0, this type is represented as LinkedList.) On the other
hand, C# has no primitive wrapper
classes, but allows boxing of any
value type, returning a generic Object
reference.
The boxed object is always a copy of
the value object, and is usually
immutable. Unboxing the object also
returns a copy of the stored value.
Note that repeated boxing and unboxing
of objects can have a severe
performance impact, since it
dynamically allocates new objects and
then makes them eligible for Garbage
collection.
Performance issue is one of the problems since we need auto-boxing for this to be achieved. Also some of the structures may benefit from having null values also.

Categories