Search Results

Search found 16 results on 1 pages for 'autoboxing'.

Page 1/1 | 1 

  • Polymorphism, Autoboxing, and Implicit Conversions

    - by dbyrne
    Would you consider autoboxing in Java to be a form of polymorphism? Put another way, do you think autoboxing extends the polymorphic capabilities of Java? What about implicit conversions in Scala? My opinion is that they are both examples of polymorphism. Both features allow values of different data types to be handled in a uniform manner. My colleague disagrees with me. Who is right?

    Read the article

  • Why does autoboxing in Java allow me to have 3 possible values for a boolean?

    - by John
    Reference: http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html If your program tries to autounbox null, it will throw a NullPointerException. javac will give you a compile-time error if you try to assign null to a boolean. makes sense. assigning null to a Boolean is a-ok though. also makes sense, i guess. but let's think about the fact that you'll get a NPE when trying to autounbox null. what this means is that you can't safely perform boolean operations on Booleans without null-checking or exception handling. same goes for doing math operations on an Integer. for a long time, i was a fan of autoboxing in java1.5+ because I thought it got java closer to be truly object-oriented. but, after running into this problem last night, i gotta say that i think this sucks. the compiler giving me an error when I'm trying to do stuff with an uninitialized primitive is a good thing. I think I may be misunderstanding the point of autoboxing, but at the same time I will never accept that a boolean should be able to have 3 values. can anyone explain this? what am i not getting?

    Read the article

  • Why can't the JVM just make autoboxing "just work"?

    - by Pyrolistical
    Autoboxing is rather scary. While I fully understand the difference between == and .equals I can't but help have the follow bug the hell out of me: final List<Integer> foo = Arrays.asList(1, 1000); final List<Integer> bar = Arrays.asList(1, 1000); System.out.println(foo.get(0) == bar.get(0)); System.out.println(foo.get(1) == bar.get(1)); That prints true false Why did they do it this way? It something to do with cached Integers, but if that is the case why don't they just cache all Integers used by the program? Or why doesn't the JVM always auto unbox to primitive? Printing false false or true true would have been way better.

    Read the article

  • Why can't the compiler/JVM just make autoboxing "just work"?

    - by Pyrolistical
    Autoboxing is rather scary. While I fully understand the difference between == and .equals I can't but help have the follow bug the hell out of me: final List<Integer> foo = Arrays.asList(1, 1000); final List<Integer> bar = Arrays.asList(1, 1000); System.out.println(foo.get(0) == bar.get(0)); System.out.println(foo.get(1) == bar.get(1)); That prints true false Why did they do it this way? It something to do with cached Integers, but if that is the case why don't they just cache all Integers used by the program? Or why doesn't the JVM always auto unbox to primitive? Printing false false or true true would have been way better. EDIT I disagree about breakage of old code. By having foo.get(0) == bar.get(0) return true you already broke the code. Can't this be solved at the compiler level by replacing Integer with int in byte code (as long as it is never assigned null)

    Read the article

  • Usage of @specialized in traits

    - by paradigmatic
    I have a trait and an implementation looking like: trait Foo[A] { def bar[B >: A: Ordering]: Foo[B] } class FooImpl[A]( val a: A, val values: List[Foo[A]] ) extends Foo[A] { def bar[B >: A] = { /* concrete implementation */} } I would like to use the @specialized annotation on A and B to avoid autoboxing. Do I need to use it in both trait and implementation, only in implementation, or only in trait ?

    Read the article

  • Auto-(un)boxing fail for compound assignment

    - by polygenelubricants
    Thanks to the implicit casting in compound assignments and increment/decrement operators, the following compiles: byte b = 0; ++b; b++; --b; b--; b += b -= b *= b /= b %= b; b <<= b >>= b >>>= b; b |= b &= b ^= b; And thanks to auto-boxing and auto-unboxing, the following also compiles: Integer ii = 0; ++ii; ii++; --ii; ii--; ii += ii -= ii *= ii /= ii %= ii; ii <<= ii >>= ii >>>= ii; ii |= ii &= ii ^= ii; And yet, the last line in the following snippet gives compile-time error: Byte bb = 0; ++bb; bb++; --bb; bb--; // ... okay so far! bb += bb; // DOESN'T COMPILE!!! // "The operator += is undefined for the argument type(s) Byte, byte" Can anyone help me figure out what's going on here? The byte b version compiles just fine, so shouldn't Byte bb just follow suit and do the appropriate boxing and unboxing as necessary to accommodate?

    Read the article

  • What is the basic design idea behind the Scala for-loop implicit box/unboxing of numerical types?

    - by IODEV
    I'm trying to understand the behavior of Scala for-loop implicit box/unboxing of "numerical" types. Why does the two first fail but not the rest? 1) Fails: scala for (i:Long <- 0 to 10000000L) {} <console>:19: error: type mismatch;<br> found : Long(10000000L) required: Int for (i:Long <- 0 to 10000000L) {} ^ 2 Fails: scala for (i <- 0 to 10000000L) {} <console>:19: error: type mismatch; found : Long(10000000L) required: Int for (i <- 0 to 10000000L) {} ^ 3) Works: scala for (i:Long <- 0L to 10000000L) {} 4) Works: scala for (i <- 0L to 10000000L) {}

    Read the article

  • Wrappers of primitive types in arraylist vs arrays

    - by ismail marmoush
    Hi, In "Core java 1" I've read CAUTION: An ArrayList is far less efficient than an int[] array because each value is separately wrapped inside an object. You would only want to use this construct for small collections when programmer convenience is more important than efficiency. But in my software I've already used Arraylist instead of normal arrays due to some requirements, though "The software is supposed to have high performance and after I've read the quoted text I started to panic!" one thing I can change is changing double variables to Double so as to prevent auto boxing and I don't know if that is worth it or not, in next sample algorithm public void multiply(final double val) { final int rows = getSize1(); final int cols = getSize2(); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { this.get(i).set(j, this.get(i).get(j) * val); } } } My question is does changing double to Double makes a difference ? or that's a micro optimizing that won't affect anything ? keep in mind I might be using large matrices.2nd Should I consider redesigning the whole program again ?

    Read the article

  • Object or primitive type

    - by John
    Hi, Can someone explain to me the usage of Integer, Boolean etc in place of their primitive types in JAVA? I can't seem to grasp the advantages their are providing. They seem to create unnecessary problems of handling null values. Thanks!

    Read the article

  • Is it guaranteed that new Integer(i) == i in Java?

    - by polygenelubricants
    Consider the following snippet: int i = 99999999; byte b = 99; short s = 9999; Integer ii = Integer.valueOf(9); // should be within cache System.out.println(new Integer(i) == i); // "true" System.out.println(new Integer(b) == b); // "true" System.out.println(new Integer(s) == s); // "true" System.out.println(new Integer(ii) == ii); // "false" It's obvious why the last line will ALWAYS prints "false": we're using == reference identity comparison, and a new object will NEVER be == to an already existing object. The question is about the first 3 lines: are those comparisons guaranteed to be on the primitive int, with the Integer auto-unboxed? Are there cases where the primitive would be auto-boxed instead, and reference identity comparisons are performed? (which would all then be false!)

    Read the article

  • Why is this code invalid in C#?

    - by mmattax
    The following code will not compile: string foo = "bar"; Object o = foo == null ? DBNull.Value : foo; I get: Error 1 Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DBNull' and 'string' To fix this, I must do something like this: string foo = "bar"; Object o = foo == null ? DBNull.Value : (Object)foo; This cast seems pointless as this is certainly legal: string foo = "bar"; Object o = foo == null ? "gork" : foo; It seems to me that when the ternary branches are of different types, the compiler will not autobox the values to the type object...but when they are of the same type then the autoboxing is automatic. In my mind the first statement should be legal... Can anyone describe why the compiler does not allow this and why the designers of C# chose to do this? I believe this is legal in Java...Though I have not verified this. Thanks. EDIT: I am asking for an understanding of why Java and C# handle this differently, what is going on underneath the scenes in C# that make this invalid. I know how to use ternary, and am not looking for a "better way" to code the examples. I understand the rules of ternary in C#, but I want to know WHY... EDIT (Jon Skeet): Removed "autoboxing" tag as no boxing is involved in this question.

    Read the article

  • SCJP question: Method ambiguous

    - by Markos Fragkakis
    Take a look at this code: public class Test { public static void main(String... args) { flipFlop("hello", new Integer(4), 2004); // flipFlop("hello", 10, 2004); // this works! } private static void flipFlop(String str, int i, Integer iRef) { System.out.println(str + " (String, int, Integer)"); } private static void flipFlop(String str, int i, int j) { System.out.println(str + " (String, int, int)"); } } The compiler gives an error that the invocation is ambiguous: Description Resource Path Location Type The method flipFlop(String, int, Integer) is ambiguous for the type Test Test.java scjp19 - inheritence/src line 3 Java Problem But if the commented-out line is used ti invoke flip-flop, the method is unambiguously invoked (the second one, because autoboxing comes after using the primitive itself). I would expect the compiler to see that the second argument will be unboxed one way or the other, and judge what method must be invoked depending on the third argument. Why does not this happen? What is the rationale?

    Read the article

  • need help with Java solution /newbie

    - by Racket
    Hi, I'm new to programming in general so i'm trying to be as specific as possible in this question. There's this book that i'm doing some exercises on. I managed to do more than half of what they say, but it's just one input that I have been struggling to find out. I'll write the question and thereafter my code, "Write an application that creates and prints a random phone number of the form XXX-XXX-XXXX. Include the dashes in the output. Do not let the first three digits contain an 8 or 9 (but don't be more restrictive than that), and make sure that the second set of three digits is not greater than 742. Hint: Think through the easiest way to construct the phone number. Each diigit does not have to be determined separately." OK, the highlighted sentence is what i'm looking at. Here's my code: import java.util.Random; public class PP33 { public static void main (String[] args) { Random rand = new Random(); int num1, num2, num3; num1 = rand.nextInt(900) + 100; num2 = rand.nextInt(643) + 100; num3 = rand.nextInt(9000) + 1000; System.out.println(num1+"-"+num2+"-"+num3); } } How am I suppose to do this? I'm on chapter 3 so we have not yet discussed if statements etcetera, but Aliases, String class, Packages, Import declaration, Random Class, Math Class, Formatting output (decimal- & numberFormat), Printf, Enumeration & Wrapper classes + autoboxing. So consider answer the question based only on these assumptions, please. The code doesn't have any errors. Thank you!

    Read the article

  • How to avoid repetition when working with primitive types?

    - by I82Much
    I have the need to perform algorithms on various primitive types; the algorithm is essentially the same with the exception of which type the variables are. So for instance, /** * Determine if <code>value</code> is the bitwise OR of elements of <code>validValues</code> array. * For instance, our valid choices are 0001, 0010, and 1000. * We are given a value of 1001. This is valid because it can be made from * ORing together 0001 and 1000. * On the other hand, if we are given a value of 1111, this is invalid because * you cannot turn on the second bit from left by ORing together those 3 * valid values. */ public static boolean isValid(long value, long[] validValues) { for (long validOption : validValues) { value &= ~validOption; } return value != 0; } public static boolean isValid(int value, int[] validValues) { for (int validOption : validValues) { value &= ~validOption; } return value != 0; } How can I avoid this repetition? I know there's no way to genericize primitive arrays, so my hands seem tied. I have instances of primitive arrays and not boxed arrays of say Number objects, so I do not want to go that route either. I know there are a lot of questions about primitives with respect to arrays, autoboxing, etc., but I haven't seen it formulated in quite this way, and I haven't seen a decisive answer on how to interact with these arrays. I suppose I could do something like: public static<E extends Number> boolean isValid(E value, List<E> numbers) { long theValue = value.longValue(); for (Number validOption : numbers) { theValue &= ~validOption.longValue(); } return theValue != 0; } and then public static boolean isValid(long value, long[] validValues) { return isValid(value, Arrays.asList(ArrayUtils.toObject(validValues))); } public static boolean isValid(int value, int[] validValues) { return isValid(value, Arrays.asList(ArrayUtils.toObject(validValues))); } Is that really much better though? Any thoughts in this matter would be appreciated.

    Read the article

  • Java replacement for C macros

    - by thkala
    Recently I refactored the code of a 3rd party hash function from C++ to C. The process was relatively painless, with only a few changes of note. Now I want to write the same function in Java and I came upon a slight issue. In the C/C++ code there is a C preprocessor macro that takes a few integer variables names as arguments and performs a bunch of bitwise operations with their contents and a few constants. That macro is used in several different places, therefore its presence avoids a fair bit of code duplication. In Java, however, there is no equivalent for the C preprocessor. There is also no way to affect any basic type passed as an argument to a method - even autoboxing produces immutable objects. Coupled with the fact that Java methods return a single value, I can't seem to find a simple way to rewrite the macro. Avenues that I considered: Expand the macro by hand everywhere: It would work, but the code duplication could make things interesting in the long run. Write a method that returns an array: This would also work, but it would repeatedly result into code like this: long tmp[] = bitops(k, l, m, x, y, z); k = tmp[0]; l = tmp[1]; m = tmp[2]; x = tmp[3]; y = tmp[4]; z = tmp[5]; Write a method that takes an array as an argument: This would mean that all variable names would be reduced to array element references - it would be rather hard to keep track of which index corresponds to which variable. Create a separate class e.g. State with public fields of the appropriate type and use that as an argument to a method: This is my current solution. It allows the method to alter the variables, while still keeping their names. It has the disadvantage, however, that the State class will get more and more complex, as more macros and variables are added, in order to avoid copying values back and forth among different State objects. How would you rewrite such a C macro in Java? Is there a more appropriate way to deal with this, using the facilities provided by the standard Java 6 Development Kit (i.e. without 3rd party libraries or a separate preprocessor)?

    Read the article

  • A Look Inside JSR 360 - CLDC 8

    - by Roger Brinkley
    If you didn't notice during JavaOne the Java Micro Edition took a major step forward in its consolidation with Java Standard Edition when JSR 360 was proposed to the JCP community. Over the last couple of years there has been a focus to move Java ME back in line with it's big brother Java SE. We see evidence of this in JCP itself which just recently merged the ME and SE/EE Executive Committees into a single Java Executive Committee. But just before that occurred JSR 360 was proposed and approved for development on October 29. So let's take a look at what changes are now being proposed. In a way JSR 360 is returning back to the original roots of Java ME when it was first introduced. It was indeed a subset of the JDK 4 language, but as Java progressed many of the language changes were not implemented in the Java ME. Back then the tradeoff was still a functionality, footprint trade off but the major market was feature phones. Today the market has changed and CLDC, while it will still target feature phones, will have it primary emphasis on embedded devices like wireless modules, smart meters, health care monitoring and other M2M devices. The major changes will come in three areas: language feature changes, library changes, and consolidating the Generic Connection Framework.  There have been three Java SE versions that have been implemented since JavaME was first developed so the language feature changes can be divided into changes that came in JDK 5 and those in JDK 7, which mostly consist of the project Coin changes. There were no language changes in JDK 6 but the changes from JDK 5 are: Assertions - Assertions enable you to test your assumptions about your program. For example, if you write a method that calculates the speed of a particle, you might assert that the calculated speed is less than the speed of light. In the example code below if the interval isn't between 0 and and 1,00 the an error of "Invalid value?" would be thrown. private void setInterval(int interval) { assert interval > 0 && interval <= 1000 : "Invalid value?" } Generics - Generics add stability to your code by making more of your bugs detectable at compile time. Code that uses generics has many benefits over non-generic code with: Stronger type checks at compile time. Elimination of casts. Enabling programming to implement generic algorithms. Enhanced for Loop - the enhanced for loop allows you to iterate through a collection without having to create an Iterator or without having to calculate beginning and end conditions for a counter variable. The enhanced for loop is the easiest of the new features to immediately incorporate in your code. In this tip you will see how the enhanced for loop replaces more traditional ways of sequentially accessing elements in a collection. void processList(Vector<string> list) { for (String item : list) { ... Autoboxing/Unboxing - This facility eliminates the drudgery of manual conversion between primitive types, such as int and wrapper types, such as Integer.  Hashtable<Integer, string=""> data = new Hashtable<>(); void add(int id, String value) { data.put(id, value); } Enumeration - Prior to JDK 5 enumerations were not typesafe, had no namespace, were brittle because they were compile time constants, and provided no informative print values. JDK 5 added support for enumerated types as a full-fledged class (dubbed an enum type). In addition to solving all the problems mentioned above, it allows you to add arbitrary methods and fields to an enum type, to implement arbitrary interfaces, and more. Enum types provide high-quality implementations of all the Object methods. They are Comparable and Serializable, and the serial form is designed to withstand arbitrary changes in the enum type. enum Season {WINTER, SPRING, SUMMER, FALL}; } private Season season; void setSeason(Season newSeason) { season = newSeason; } Varargs - Varargs eliminates the need for manually boxing up argument lists into an array when invoking methods that accept variable-length argument lists. The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments. Varargs can be used only in the final argument position. void warning(String format, String... parameters) { .. for(String p : parameters) { ...process(p);... } ... } Static Imports -The static import construct allows unqualified access to static members without inheriting from the type containing the static members. Instead, the program imports the members either individually or en masse. Once the static members have been imported, they may be used without qualification. The static import declaration is analogous to the normal import declaration. Where the normal import declaration imports classes from packages, allowing them to be used without package qualification, the static import declaration imports static members from classes, allowing them to be used without class qualification. import static data.Constants.RATIO; ... double r = Math.cos(RATIO * theta); Annotations - Annotations provide data about a program that is not part of the program itself. They have no direct effect on the operation of the code they annotate. There are a number of uses for annotations including information for the compiler, compiler-time and deployment-time processing, and run-time processing. They can be applied to a program's declarations of classes, fields, methods, and other program elements. @Deprecated public void clear(); The language changes from JDK 7 are little more familiar as they are mostly the changes from Project Coin: String in switch - Hey it only took us 18 years but the String class can be used in the expression of a switch statement. Fortunately for us it won't take that long for JavaME to adopt it. switch (arg) { case "-data": ... case "-out": ... Binary integral literals and underscores in numeric literals - Largely for readability, the integral types (byte, short, int, and long) can also be expressed using the binary number system. and any number of underscore characters (_) can appear anywhere between digits in a numerical literal. byte flags = 0b01001111; long mask = 0xfff0_ff08_4fff_0fffl; Multi-catch and more precise rethrow - A single catch block can handle more than one type of exception. In addition, the compiler performs more precise analysis of rethrown exceptions than earlier releases of Java SE. This enables you to specify more specific exception types in the throws clause of a method declaration. catch (IOException | InterruptedException ex) { logger.log(ex); throw ex; } Type Inference for Generic Instance Creation - Otherwise known as the diamond operator, the type arguments required to invoke the constructor of a generic class can be replaced with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context.  map = new Hashtable<>(); Try-with-resource statement - The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement.  try (DataInputStream is = new DataInputStream(...)) { return is.readDouble(); } Simplified varargs method invocation - The Java compiler generates a warning at the declaration site of a varargs method or constructor with a non-reifiable varargs formal parameter. Java SE 7 introduced a compiler option -Xlint:varargs and the annotations @SafeVarargs and @SuppressWarnings({"unchecked", "varargs"}) to supress these warnings. On the library side there are new features that will be added to satisfy the language requirements above and some to improve the currently available set of APIs.  The library changes include: Collections update - New Collection, List, Set and Map, Iterable and Iteratator as well as implementations including Hashtable and Vector. Most of the work is too support generics String - New StringBuilder and CharSequence as well as a Stirng formatter. The javac compiler  now uses the the StringBuilder instead of String Buffer. Since StringBuilder is synchronized there is a performance increase which has necessitated the wahat String constructor works. Comparable interface - The comparable interface works with Collections, making it easier to reuse. Try with resources - Closeable and AutoCloseable Annotations - While support for Annotations is provided it will only be a compile time support. SuppressWarnings, Deprecated, Override NIO - There is a subset of NIO Buffer that have been in use on the of the graphics packages and needs to be pulled in and also support for NIO File IO subset. Platform extensibility via Service Providers (ServiceLoader) - ServiceLoader interface dos late bindings of interface to existing implementations. It helpe to package an interface and behavior of the implementation at a later point in time.Provider classes must have a zero-argument constructor so that they can be instantiated during loading. They are located and instantiated on demand and are identified via a provider-configuration file in the METAINF/services resource directory. This is a mechansim from Java SE. import com.XYZ.ServiceA; ServiceLoader<ServiceA> sl1= new ServiceLoader(ServiceA.class); Resources: META-INF/services/com.XYZ.ServiceA: ServiceAProvider1 ServiceAProvider2 ServiceAProvider3 META-INF/services/ServiceB: ServiceBProvider1 ServiceBProvider2 From JSR - I would rather use this list I think The Generic Connection Framework (GCF) was previously specified in a number of different JSRs including CLDC, MIDP, CDC 1.2, and JSR 197. JSR 360 represents a rare opportunity to consolidated and reintegrate parts that were duplicated in other specifications into a single specification, upgrade the APIs as well provide new functionality. The proposal is to specify a combined GCF specification that can be used with Java ME or Java SE and be backwards compatible with previous implementations. Because of size limitations as well as the complexity of the some features like InvokeDynamic and Unicode 6 will not be included. Additionally, any language or library changes in JDK 8 will be not be included. On the upside, with all the changes being made, backwards compatibility will still be maintained. JSR 360 is a major step forward for Java ME in terms of platform modernization, language alignment, and embedded support. If you're interested in following the progress of this JSR see the JSR's java.net project for details of the email lists, discussions groups.

    Read the article

1