DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

The Latest Languages Topics

article thumbnail
Mocking Static Methods in Groovy
Using Groovy to test not only other Groovy classes but also Java classes is an increasing popular approach given frameworks like Spock which facilitate Test Driven and Behaviour Driven Development. A common problem when testing though is having to deal with legacy code and more often than not having to mock static methods calls. When writing tests in Groovy, the approach to mocking static calls will depend on the type of class you're testing and what type of class has the static method in. If the Groovy class you're testing makes calls a static method on another Groovy class, then you could use the ExpandoMetaClass which allows you to dynamically add methods, constructors, properties and static methods. The below Account Groovy class has a static method called getType(). The Customer Groovy class you're trying to test calls the getType() static method within it's getAccountType() method: class Customer { String getAccountType() { return Account.getType(); } } class Account { static String getType() { return "Personal"; } } class CustomerTest extends GroovyTestCase { void testGetAccountType() { Customer cust = new Customer() assert cust.getAccountType() == "Personal" Account.metaClass.static.getType = {return "Business"} assert cust.getAccountType() == "Business" } } The CustomerTest Groovy class shows how the getType static method can be overridden using the metaClass property. This isn't strictly mocking, more dynamically changing a class. An alternative approach is to use Spock's GroovyMock to achieve a similar result. (A more detailed description of Spock's mocking and stubbing features can be found here:) import spock.lang.* class CustomerTest extends Specification { def "get account type"() { setup: GroovyMock(Account, global: true) Account.getType() >> "Business" Customer cust = new Customer() when: "obtaining a customer's account type" def type = cust.getAccountType() then: "the type will be a Business account" type == "Business" } } If the Account class is a Java not Groovy class then we can still mock it out using the above methods. The problem with mocking Java static methods though, when using Groovy for testing, is when they are called from Java classes and these calling classes are the ones you are trying to test. For example, if we now have a Customer Java class and also an Account Java class, and a CustomerTest Groovy class, the ExpandoMetaClass and GroovyMock approaches will not work globally but will work locally. The below CustomerTest will pass. public class Customer { public String getAccountType() { return Account.getType(); } } public class Account { public static String getType() { return "Personal"; } } class CustomerTest extends GroovyTestCase { void testGetAccountType() { Customer cust = new Customer() assert cust.getAccountType() == "Personal" Account.metaClass.static.getType = {return "Business"} assert Account.getType() == "Business" assert cust.getAccountType() == "Personal" } } The way around this is to use a mocking framework like Powermock or JMockit. The below amended CustomerTest Groovy class shows how Powermock can be integrated into a GroovyTestCase: import groovy.mock.interceptor.* import org.powermock.api.mockito.PowerMockito; import static org.mockito.Mockito.*; import org.powermock.core.classloader.annotations.PrepareForTest import org.junit.runner.RunWith; import org.powermock.modules.junit4.PowerMockRunner @RunWith( PowerMockRunner.class ) @PrepareForTest(Account.class) class CustomerTest extends GroovyTestCase { public void testGetAccountType() { Customer cust = new Customer() assert cust.getAccountType() == "Personal" PowerMockito.mockStatic(Account.class); when(Account.getType()).thenReturn("Business"); assert cust.getAccountType() == "Business" } } Using Mockito's when to mock the return value of the static getType() call enables "Business" to be returned instead of "Personal". This example shows how when writing Groovy tests to test Java classes, using a framework like Powermock can fill the void of mocking Java static methods when called from the Java classes you are trying to test.
April 15, 2013
by Geraint Jones
· 92,803 Views · 8 Likes
article thumbnail
Java Lambda Expressions Basics
Learn about Java Lambda essentials, including basics and examples.
April 13, 2013
by Edwin Dalorzo
· 293,493 Views · 24 Likes
article thumbnail
Scala Traits Implementation and Interoperability. Part I: Basics
Traits in Scala are similar to interfaces, but much more powerful. They allow implementations of some of the methods, fields, stacking, etc. But have you ever wondered how are they implemented on top of JVM? How is it possible to extend multiple traits and where the implementations go to? In this article, based on my StackOverflow answer, I will give several trait examples and explain how scalac implements them, what are the drawbacks and what you get for free. Often we will look at compiled classes and decompile them to Java. It's not essential knowledge, but I hope you'll enjoy it. All examples are compiled against Scala 2.10.1. Simple trait with no method implementations The following trait: trait Solver { def answer(question: String): Int } compiles down to the most boring Java interface: public interface Solver { int answer(String); } There is really nothing special in Scala traits. That also means that if you ship Solver.class as part of your library, users can safely implement such interface from Java code. As far as java/javac is concerned, this is an ordinary Java compiled interface. Traits having some methods implemented OK, but what if trait actually has some method bodies? trait Solver { def answer(s: String): Int def ultimateAnswer = answer("Answer to the Ultimate Question of Life, the Universe, and Everything") } Here, ultimateAnswer method actually has some implementation (the fact that it calls abstract answer() method is irrelevant) while answer() remains unimplemented. What will scalac produce? public interface Solver { int answer(java.lang.String); int ultimateAnswer(); } Well, it's still an interface and the implementation is gone. If the implementation is gone, what happens when we extend such a trait? class DummySolver extends Solver { override def answer(s: String) = 42 } We need to implement answer() but ultimateAnswer is already available via Solver. Anxious to see how it looks under the hood? DummySolver.class: public class DummySolver implements Solver { public DummySolver() { Solver$class.$init$(this); } public int ultimateAnswer() { return Solver$class.ultimateAnswer(this); } public int answer(String s) { return 42; } } That... is... weird... Apparently we missed one new class file, Solver$class.class. Yes, the class is named Solver$class, this is valid even in Java. This is not Solver.class expression which returns Class[Solver], it's apparently an ordinary Java class named Solver$class with a bunch of static methods. Here is how it looks like: public abstract class Solver$class { public static int ultimateAnswer(Solver $this) { return $this.answer("Answer to the Ultimate Question of Life, the Universe, and Everything"); } public static void $init$(Solver solver) {} } Do you see the trick? Scala created a helper Solver$class and methods that are implemented inside trait are actually placed in that hidden class. BTW this is not a companion object, it's just a helper class invisible to you. But the real trick is $this parameter, invoked as Solver$class.ultimateAnswer(this). Since we are technically in another object, we must somehow get a handle of a real Solver instance. It is like OOP but done manually. So we learned that method implementations from traits are extracted to a special helper class. This class is referenced every time we call such a method. This way we don't copy method body over and over into every single class extending given trait. Extending multiple traits with implementations Imagine extending multiple traits, each implementing distinct set of methods: trait Foo { def foo = "Foo" } trait Bar { def bar = "Bar" } class Buzz extends Foo with Bar By analogy you probably know already how Foo.class and Bar.class look like: public interface Foo { String foo(); } public interface Bar { String bar(); } Implementations are hidden in mysterious ...$class.class files just as before: public abstract class Foo$class { public static String foo(Foo) { return "Foo"; } public static void $init$(Foo) {} } public abstract class Bar$class { public static String bar(Bar) { return "Bar"; } public static void $init$(Bar) {} } Notice that static methods in Foo$class accept instances of Foo while Bar$class require reference to Bar. This works because Buzz implements both Foo and Bar: public class Buzz implements Foo, Bar { public Buzz() { Foo.class.$init$(this); Bar.class.$init$(this); } public String bar() { return Bar$class.bar(this); } public String foo() { return Foo$class.foo(this); } } Both foo() and bar() pass this reference, but this is fine. Traits with fields Fields are another interesting feature of traits. This time let's use a real-world example from Spring Data project. As you know interfaces can require certain methods to be implemented. However they can't force you to provide certain fields (or provide fields on their own). This limitation becomes painful when working with Auditable interface extending Persistable. While these interfaces merely exist to make sure certain fields are present on your @Entity class, namely createdBy, createdDate, lastModifiedBy, lastModifiedDate and id, this cannot be expressed cleanly. Instead you have to implement the following methods in every single entity extending Auditable: U getCreatedBy(); void setCreatedBy(final U createdBy); DateTime getCreatedDate(); void setCreatedDate(final DateTime creationDate); U getLastModifiedBy(); void setLastModifiedBy(final U lastModifiedBy); DateTime getLastModifiedDate(); void setLastModifiedDate(final DateTime lastModifiedDate); ID getId(); boolean isNew(); Moreover, every single class must of course define fields highlighted above. Doesn't feel DRY at all. Luckily traits can help us a lot. In trait we can define what fields should be created in every class extending this trait: trait IAmAuditable[ID <: java.io.Serializable] extends Auditable[User, ID] { var createdBy: User = _ def getCreatedBy = createdBy def setCreatedBy(createdBy: User) { this.createdBy = createdBy } var createdDate: DateTime = _ def getCreatedDate = createdDate def setCreatedDate(creationDate: DateTime) { this.createdDate = creationDate } var lastModifiedBy: User = _ def getLastModifiedBy = lastModifiedBy def setLastModifiedBy(lastModifiedBy: User) { this.lastModifiedBy = lastModifiedBy } var lastModifiedDate: DateTime = _ def getLastModifiedDate = lastModifiedDate def setLastModifiedDate(lastModifiedDate: DateTime) { this.lastModifiedDate = lastModifiedDate } var id: ID = _ def getId = id def isNew = id == null } But wait, Scala has built-in support for POJO-style getters/setters! So we can shorten this to: class IAmAuditable[ID <: java.io.Serializable] extends Auditable[User, ID] { @BeanProperty var createdBy: User = _ @BeanProperty var createdDate: DateTime = _ @BeanProperty var lastModifiedBy: User = _ @BeanProperty var lastModifiedDate: DateTime = _ @BeanProperty var id: ID = _ def isNew = id == null } Compiler-generated getters and setters implement interface automatically. From now on, every class willing to provide auditing capabilities can extend this trait: @Entity class Person extends IAmAuditable[String] { //... } All the fields, getters and setters are there. But how is it implemented? Let's look at the generated Person.class: public class Person implements IAmAuditable { private User createdBy; private DateTime createdDate; private User lastModifiedBy; private DateTime lastModifiedDate; private java.io.Serializable id; public User createdBy() //... public void createdBy_$eq(User) //... public User getCreatedBy() //... public void setCreatedBy(User) //... public DateTime createdDate() //... public void createdDate_$eq(DateTime) //... public DateTime getCreatedDate() //... public void setCreatedDate(DateTime) //... public boolean isNew(); //... } There is actually much more, but you get the idea. So fields aren't refactored into a separate class, but that was to be expected. Instead fields are copied into every single class extending this particular trait. In Java we could have used abstract base class for that, but it's nice to reserve inheritance for real is-a relationships and do not use it for dummy field holders. In Scala trait is such a holder, grouping common fields that we can reuse across several classes. What about Java interoperability? Well, IAmAuditable is compiled down to Java interface, thus it doesn't have fields at all. If you implement it from Java, you gain nothing special. We covered basic use cases for traits in Scala and their implementation. In the next article we will explore how mixins and stackable modifications work.
April 11, 2013
by Tomasz Nurkiewicz
· 8,280 Views
article thumbnail
Predicate and Consumer Interface in java.util.function package in Java 8
Here's how to properly use the Predicate and Consumer interfaces in Java 8.
April 11, 2013
by Mohamed Sanaulla
· 39,633 Views · 17 Likes
article thumbnail
Monitoring with DataDog
Recently I found myself sending more and more business metrics to Datadog, a Software as a Service solution that promises to collect all your data points and build business metrics, displaying them as graphs and triggering alerts whenever they get to critically low (or high) levels. The goals The more your automated tests raises their level of abstraction, the more they become oriented to external quality (what the customer wants and does) instead of internal quality (low coupling, high cohesion of the software design). The largest end-to-end tests that we have in place at Onebip connect several different projects on an integration server and run everything from the creation of a purchase or subscription to its renewal and termination (events that would happen months after creation). However, even end-to-end tests cannot guarantee that our applications work against external resources, such as merchants, mobile carrier, and ISPs. The only way to catch integration problems is monitoring. These problems, like a mobile carrier experiencing an outage, may be due to our errors or to external conditions; but they should nevertheless be discovered as early as possible. The infrastructure Datadog is the only data-collection service that passed the stress tests of SLL, our solution architect. It ships as an UDP server that you pay basing on the number of machines you want to run it on; for example, a preproduction and a production server are a common choice to start out. The server collects data locally and periodically uploads it to Datadog in bursts, where you can access it via a web application or via APIs in case you want to call it from your build. The UDP protocol is aligned with the goals of metric collections: a silent server that decouples the sending of metrics from the rest of the business logic: UDP packets are just lost if no process is there listening to them, no errors are raised if the server crashes or is not running or installed for some reason for instance in development machines). The monitoring code, which you write, should be decoupled and asynchronous as much as possible. The part that talks over the network is already externalized in the DataDog server, but you don't want the user to wait because you have to send some strange number. So the internal part (sending via UDP) is performed in Listener objects that implement the Observer pattern. These object still have to be wrapped in all-encompassing try/catch constructs so that any errors in the monitoring part never influence the business logic. Againg, you don't want a payment to fail because of an exception in how monitoring DateTime objects are built. For PHP we built a SilentListener class to wrap all of our object: class SilentListener { private $wrapped; public function __construct($wrapped) { $this->wrapped = $wrapped; } public function __call($method, $args) { try { call_user_func_array(array($this->wrapped, $method), $args); } catch (Exception $e) { $this->log($e); } } }SLL An example In some countries, we receive payments through mobile-originated messages (MO), a fancy word for saying SMS sent by the end user. So a simple way to monitor if we are receiving payment or if the server is exploded is to upload a metric counting them every time we receive one (pseudo-JSON format to show you the data): { counter: 1 } However, we can be more precise than this: an external outage or an integration problem may happen to a lower level than the whole application. For example, MOs can be delayed in Argentina, by a single carrier, while the rest of the world is still working fine. So our data points look like this: { counter: 1, tags: { country: "IT", carrier: "Vodafone", merchant: "Tasty Cookies, Inc.", } } and in turn graphs on DataDog or calls to its API can set up filters so that we can, if necessary, view only the data related to any combination of country, carrier and merchant. The nice thing, SLL says, is that you just start send data from production and only after you have data points available you build a graph or an alert system basing on what appears to be the most important tags. For example, a big merchant may benefit from some dedicated monitoring, while minor countries such as Vietnam should be monitored as a whole since their traffic is by far lower than that of the others.
April 10, 2013
by Giorgio Sironi
· 16,428 Views · 1 Like
article thumbnail
Python: Reading a JSON File
In this post, a developer quickly guides us through the process of using Python to read files in the most prominent data transfer language, JSON.
April 10, 2013
by Mark Needham
· 231,957 Views · 4 Likes
article thumbnail
Getting Rid of Boilerplate Code with Java Lambda Expressions
As I have mentioned in a previous post, there is nothing we can do with lambda expressions that we could not do without them. Basically because we can implement a similar idiom in Java using anonymous classes. The problem is that anonymous classes require a lot of boilerplate code. To demonstrate the value of lambda expressions as a tool to achieve more succinct code in this post I will develop some classical high-order functions from scratch. Filtering Let’s consider the existence of an interface called Predicate defined as follows: interface Predicate { public boolean test(T t); } And now, let’s say we would like to use the Predicate interface to filter the elements of any given list based on a given predicate. So, we could define something as follows: static List filter(Predicate predicate, List source) { List destiny = new ArrayList<>(); for(T item : source) { if(predicate.test(item)){ destiny.add(item); } } return destiny; } Now, consider that we had a list of numbers, and we would like to filter only those that are odd. Traditionally, in Java, we would use an anonymous class to define the predicate, something like this: List numbers = asList(1,2,3,4,5,6,7,8,9); List onlyOdds = filter(new Predicate(){ @Override public boolean test(Integer n) { return n % 2 != 0; } }, numbers); But consider all the boilerplate code that was necessary here to simply say that we would like to take a value n and check if it is an odd number. Clearly this does not look good. In Java 8, we could get rid of all this mess by simply implementing our predicate using a lambda expression, as follows: List numbers = asList(1,2,3,4,5,6,7,8,9); List onlyOdds = filter(n –> n % 2 !=0, numbers); Here, the lambda expression will be evaluated to an instance of the type Predicate, its argument n, corresponds to the argument expected by its method test, and the body of the expressions represents the implementation of the method. Mapping Let’s consider now the existence of an interface Function defined as follows: interface Function { public R apply(T t); } And now, let’s say we would like to use this functional interface to transform the elements of a list from one value to another. So, we could define a method as follows: static List map(Function function, List source){ List destiny = new ArrayList<>(); for(T item : source) { R value = function.apply(item); destiny.add(value); } return destiny; } Now, consider that we had a list of strings representing numbers and we would like to convert them to their corresponding integer values. Once again, in the traditional model we could use Java anonymous classes for this, like so: List digits = asList("1","2","3","4","5","6","7","8","9"); List numbers = map(new Function digits = asList("1","2","3","4","5","6","7","8","9"); List numbers = map(s –> Integer.valueOf(s), digits); This is clearly much better. Once again, the lambda expression evaluates to an instance of the type Function where s represents the argument for its function apply and the body of the lambda expression represents what the function would return in its body. Reducing Let’s consider now the existence of an interface BinaryOperator defined as follows: interface BinaryOperator { public T apply(T left, T right); } And now we would like to use this functional interface to reduce the values from a list to a single value. So, we could use it as follows: static T reduce(BinaryOperator operator,T seed, List source){ for(T item: source) { seed = operator.apply(seed, item); } return seed; } Consider now that we have a list of numbers and we would like to obtain to summation of them all. Once more, if we intend to use this code as we traditionally have done before the release of Java 8 we would be forced to to following verbose definition, as follows: List numbers = asList(1,2,3,4,5); Integer sum = reduce(new BinaryOperator() { @Override public Integer apply(Integer left, Integer right){ return left + right; } },0,numbers); This code can be greatly simplified by the use of a lambda expression, as follows: List numbers = asList(1,2,3,4,5); Integer sum = reduce( (x,y) –> x + y, 0, numbers); Where (x,y) correspond to the two arguments left and right that the function apply receives, and the body of the expressions would be what it would return. Notice that, since in this case we have to specify two arguments, the lambda expressions is required to specify them within parenthesis, otherwise the compiler could determine which arguments are for the lambda expression and which are for the reduce method. Consuming Let’s consider now the existence of a functional interface Consumer, defined as follows: interface Consumer { public void accept(T t); } Now we could use implementations of this interface to consume the elements of a list and do something with them, like printing them to the main output or sending them over the network, or whatever we could consider appropriate. For this example, let’s just print them to the output: static void forEach(Consumer consumer, List source) { for(T item: source) { consumer.accept(item); } } Look at all the boilerplate code necessary to create a consumer to simply print all the elements of a list: List numbers = asList(1,2,3,4,5); forEach(new Consumer(){ @Override public void accept(Integer n) { System.out.println(n); } },numbers); However, now we could use a simple lambda expression to implement equivalent functionality as follows: List numbers = asList(1,2,3,4,5); forEach(n –> { System.out.println(n); }, numbers); The syntax differs a bit from the previous cases because in this case the method we intend to implement through the lambda expression returns void, and that is why we use a code block to signify that the type of the lambda expression is also void. Producing Let’s consider now the existence of a functional interface Supplier as follows: interface Supplier { public T get(); } A classical idiom is to use this type of interface to encapsulate an expensive calculation and differ its evaluation until needed, something typically known as lazy evaluation. For example: public static int generateX() { return 0; } public static int generateY() { //some expensive calculation here return 1; } public static int calculate(Supplier thunkOfX, Supplier thunkOfY) { int x = thunkOfX.get(); if(x==0) return 0; else return x + thunkOfY.get(); } By means of passing two suppliers here we defer the evaluation of x and y until needed. As you can see, if x is equal to 0, y is never needed. So, by using this idiom we avoid spending a lot of time in a expensive calculation unnecessarily. Before lambda expressions, the invocation of calculation would have implied a lot of boilerplate code as follows: calculate(new Supplier() { @Override public Integer get() { return generateX(); } }, new Supplier() { @Override public Integer get() { return generateY(); } }); However, using lambda expressions, this a one-liner: calculate( () –> generateX(), () –> generateY() ); Clearly this is much better. Summary of Lambda Syntax So, these are different ways to define lambda expressions: Predicate isOdd = n –> n % 2 == 0; Function atoi = s –> Integer.valueOf(s); BinaryOperator product = (x, y) –> x * y Comparator maxInt = (x,y) –> x > y ? x : y; Consumer printer = s –> { System.out.println(s); }; Supplier producer = () –> "Hello World"; Runnable task = () –> { System.out.println("I am a runnable task"); }; In summary, lambda expressions are a great tool to get rid of all the boilerplate required by the clunky Java syntax of anonymous classes. The new API for Streams makes extensive use of this new syntax: int oddSum = asList("1","2","3","4","5").stream() .map(n –> Integer.valueOf(n)) .filter(n –> n % 2 != 0) .reduce(0, (x,y) –> x + y); // 9
April 10, 2013
by Edwin Dalorzo
· 6,947 Views
article thumbnail
Java Lambda Expressions vs Method References
Now we can use lambda expressions to implement functional interfaces as we have seen in previous posts, but the lambda expressions are not the only mechanism we can use for this purpose. Particularly where there are preexisting code that we would like to reuse we can simplify the implementation of the functional interface by using method references. Static Method References First, consider the existence of a functional interface Predicate as follows: public interface Predicate { public void test(T t); } And let’s say that we had a method to filter elements out of a list using this predicate, as follows: static List filter(Predicate predicate, List source) { List destiny = new ArrayList<>(); for (T item : source) { if(predicate.test(item)){ destiny.add(item); } } return destiny; } Finally, let’s say we had a class containing a set of static method predicates which we had defined in the past, prior to the existence of the Java 8. Something as follows: static class IntPredicates { public static boolean isOdd(Integer n) { return n % 2 != 0; } public static boolean isEven(Integer n) { return n % 2 == 0; } public static boolean isPositive(Integer n) { return n >= 0; } } Now, one way to implement a predicate that could reuse our static methods would be through the use of lambda expressions, like this: Predicate isOdd = n -> IntPredicates.isOdd(n); Predicate isEven = n -> IntPredicates.isEven(n); However, we can clearly see that the signature of the static predicate methods corresponds perfectly with the signature of the test method for integer predicates. So, an alternative way to implement the functional interface in this case is through a static method reference, as follows: Predicate isOdd = IntPredicates::isOdd; Predicate isEven = IntPredicate::isEven; Notice the use of double colon :: here. We are not invoking the method, we are just referencing its name. We could now use this technique to filter a list of numbers that satisfy any of these predicates, something like this: List numbers = asList(1,2,3,4,5,6,7,8,9); List odds = filter(IntPredicates::isOdd, numbers); List evens = filter(IntPredicates::isEven, numbers); So, as we can see, we could implement the functional interfaces in this case using both: lambda expressions and method references, but the syntax with the static method references was more succinct. Constructor Method References Let’s consider now the existence of a functional interface named Function, as follows: public interface Function { public R apply(T t); } Based on it, we could define a method map, that converts the elements from a source list from certain value T to certain value R, as follows: static List map(Function function, List source) { List destiny = new ArrayList<>(); for (T item : source) { R value = function.apply(item); destiny.add(value); } return destiny; } Now imagine that we had a list of strings containing numbers that we would like to transform to integer values. We could do it using a lambda expression to provide an implementation for the Function interface, more or less like this: List digits = asList("1","2","3","4","5"); List numbers = map(s -> new Integer(s), digits); However, we can clearly infer that the constructor Integer(String) has the same signature as the apply method in the Function reference required here, namely, it receives a string as argument and returns an integer. So, in this case we simplify the implementation of the functional interface by means of using a constructor reference, as follows: List digits = asList("1","2","3","4","5"); List numbers = map(Integer::new, digits); This conveys the same meaning: take a string and make me an integer out of it. It is the perfect task for our Integer(String) constructor. Instance Method Reference to Arbitrary Objects Consider now the existence of a class named Jedi, defined as follows: public class Jedi { private String name; private int power; public Jedi(String name, int power){ this.name = name; this.power = power; } public String getName() { return name; } public int getPower() { return power; } //equals,hashCode,toString } Now, consider that we had a list of jedis, and we would like to use our previous function map to extract the name from every jedi and generate a list of names out of the list of jedis. Somewhat like this, using lambda expressions: List jedis = asList(new Jedi("Obi-wan", 80), new Jedi("Anakin", 25), new Jedi("Yoda", 500)); List names = map(jedi -> jedi.getName() , jedis); The interesting observation here is that the parameter jedi is the argument for the apply method in the Function reference. And we use that reference to a jedi to invoke on it the method getName. In other words, we invoke a method on the reference we receive as argument. So, we could simplify this implementation by using an instance method reference as follows: List jedi = asList(new Jedi("Obi-wan", 80), new Jedi("Anakin", 25), new Jedi("Yoda", 500)); List names = map(Jedi::getName, jedi); Again, the interesting aspect of this type of method reference is that the method getName is an instance method. Therefore, the target of its invocation must be an instance, which in this case is an arbitrary object being provided as the argument for the method apply in the Function interface definition. Instance Method Reference to a Specific Object Let’s consider the existence of functional interface named Consumer, as follows public interface Consumer { public void accept(T t); } And let’s define a method capable of using a consumer to consume all the elements of a given list, like this: static void forEach(Consumer consumer, List source){ for (T item : source) { consumer.accept(item); } } Imagine that now we would like to print all the elements contained in a list, and for that purpose we could define a consumer using a lambda expressions: List numbers = asList(1,2,3,4,5,6,7,8,9); forEach(n -> { System.out.println(n); }, numbers); However, we could also make the observation that the method println has the same signature that our Consumer has, it receives an integer and does something with it, in this case it prints it to the main output. However, we cannot specify that this is an arbitrary instance method reference by saying PrintStream::println, because in this case the Consumer interface method accept does not receive as one of its arguments the PrintStream object on which we may want to invoke the method println. Conversely, we already know which is the target object on which we would like to invoke the method: we can see that every time we would like to invoke it on a specific reference, in this case the object System.out. So, we could implement our functional interface using an instance method reference to a specific object as follows: List numbers = asList(1,2,3,4,5,6,7,8,9); forEach(System.out::println, numbers); In summary, there are circumstances in which we would like to use some preexisting code as the implementation for a functional interface, in those case we could use one of several variants of method references instead of a more verbose lambda expression.
April 9, 2013
by Edwin Dalorzo
· 79,556 Views · 5 Likes
article thumbnail
Covariance and Contravariance In Java
I have found that in order to understand covariance and contravariance a few examples with Java arrays are always a good start. Arrays Are Covariant Arrays are said to be covariant which basically means that, given the subtyping rules of Java, an array of type T[] may contain elements of type T or any subtype of T. For instance: Number[] numbers = newNumber[3]; numbers[0] = newInteger(10); numbers[1] = newDouble(3.14); numbers[2] = newByte(0); But not only that, the subtyping rules of Java also state that an array S[] is a subtype of the array T[] if S is a subtype of T, therefore, something like this is also valid: Integer[] myInts = {1,2,3,4}; Number[] myNumber = myInts; Because according to the subtyping rules in Java, an array Integer[] is a subtype of an array Number[] because Integer is a subtype of Number. But this subtyping rule can lead to an interesting question: what would happen if we try to do this? myNumber[0] = 3.14; //attempt of heap pollution This last line would compile just fine, but if we run this code, we would get an ArrayStoreException because we’re trying to put a double into an integer array. The fact that we are accessing the array through a Number reference is irrelevant here, what matters is that the array is an array of integers. This means that we can fool the compiler, but we cannot fool the run-time type system. And this is so because arrays are what we call a reifiable type. This means that at run-time Java knows that this array was actually instantiated as an array of integers which simply happens to be accessed through a reference of type Number[]. So, as we can see, one thing is the actual type of the object, an another thing is the type of the reference that we use to access it, right? The Problem with Java Generics Now, the problem with generic types in Java is that the type information for type parameters is discarded by the compiler after the compilation of code is done; therefore this type information is not available at run time. This process is called type erasure. There are good reasons for implementing generics like this in Java, but that’s a long story, and it has to do with binary compatibility with pre-existing code. The important point here is that since at run-time there is no type information, there is no way to ensure that we are not committing heap pollution. Let’s consider now the following unsafe code: List myInts = newArrayList(); myInts.add(1); myInts.add(2); List myNums = myInts; //compiler error myNums.add(3.14); //heap polution If the Java compiler does not stop us from doing this, the run-time type system cannot stop us either, because there is no way, at run time, to determine that this list was supposed to be a list of integers only. The Java run-time would let us put whatever we want into this list, when it should only contain integers, because when it was created, it was declared as a list of integers. That’s why the compiler rejects line number 4 because it is unsafe and if allowed could break the assumptions of the type system. As such, the designers of Java made sure that we cannot fool the compiler. If we cannot fool the compiler (as we can do with arrays) then we cannot fool the run-time type system either. As such, we say that generic types are non-reifiable, since at run time we cannot determine the true nature of the generic type. Evidently this property of generic types in Java would have a negative impact on polymorphism. Let’s consider now the following example: staticlongsum(Number[] numbers) { longsummation = 0; for(Number number : numbers) { summation += number.longValue(); } returnsummation; } Now we could use this code as follows: Integer[] myInts = {1,2,3,4,5}; Long[] myLongs = {1L, 2L, 3L, 4L, 5L}; Double[] myDoubles = {1.0, 2.0, 3.0, 4.0, 5.0}; System.out.println(sum(myInts)); System.out.println(sum(myLongs)); System.out.println(sum(myDoubles)); But if we attempt to implement the same code with generic collections, we would not succeed: staticlongsum(List numbers) { longsummation = 0; for(Number number : numbers) { summation += number.longValue(); } returnsummation; } Because we we would get compiler errors if you try to do the following: List myInts = asList(1,2,3,4,5); List myLongs = asList(1L, 2L, 3L, 4L, 5L); List myDoubles = asList(1.0, 2.0, 3.0, 4.0, 5.0); System.out.println(sum(myInts)); //compiler error System.out.println(sum(myLongs)); //compiler error System.out.println(sum(myDoubles)); //compiler error The problem is that now we cannot consider a list of integers to be subtype of a list of numbers, as we saw above, that would be considered unsafe for the type system and compiler rejects it immediately. Evidently, this is affecting the power of polymorphism and it needs to be fixed. The solution consists in learning how to use two powerful features of Java generics known as covariance and contravariance. Covariance For this case, instead of using a type T as the type argument of a given generic type, we use a wildcard declared as ? extends T, where T is a known base type. With covariance we can read items from a structure, but we cannot write anything into it. All these are valid covariant declarations. List myNums = newArrayList(); List myNums = newArrayList(); List myNums = newArrayList(); And we can read from our generic structure myNums by doing: Number n = myNums.get(0); Because we can be sure that whatever the actual list contains, it can be upcasted to a Number (after all anything that extends Number is a Number, right?) However, we are not allowed to put anything into a covariant structure. myNumst.add(45L); //compiler error This would not be allowed because the compiler cannot determine what is the actual type of the object in the generic structure. It can be anything that extends Number (like Integer, Double, Long), but the compiler cannot be sure what, and therefore any attempt to retrieve a generic value is considered an unsafe operation and it is immediately rejected by the compiler. So we can read, but not write. Contravariance For contravariance we use a different wildcard called ? super T, where T is our base type. With contravariance we can do the opposite. We can put things into a generic structure, but we cannot read anything out of it. In this case, the actual nature of the object is List of Object, and through contravariance, we can put a Number in it, basically because a Number has Object as its common ancestor. As such, all numbers are also objects, and therefore this is valid. However, we cannot safely read anything from this contravariant structure assuming that we will get a number. Number myNum = myNums.get(0); //compiler-error As we can see, if the compiler allowed us to write this line, we would get a ClassCastException at run time. So, once again, the compiler does not run the risk of allowing this unsafe operation and rejects it immediately. Get/Put Principle In summary, we use covariance when we only intend to take generic values out of a structure. We use contravariance when we only intend to put generic values into a structure and we use an invariant when we intend to do both. The best example I have is the following that copies any kind of numbers from one list into another list. It only gets items from the source, and it only puts items in the destiny. publicstaticvoidcopy(List source, List destiny) { for(Number number : source) { destiny.add(number); } } Thanks to the powers of covariance and contravariance this works for a case like this: List myInts = asList(1,2,3,4); List myDoubles = asList(3.14, 6.28); List
April 8, 2013
by Edwin Dalorzo
· 139,882 Views · 28 Likes
article thumbnail
Function Interface- A Functional Interface in the java.util.function Package in Java 8
I had previously written about functional interfaces and their usage. If you are exploring the APIs to be part of Java 8 and especially those APIs which support lambda expressions you will find few interfaces like- Function, Supplier, Consumer, Predicate and others which are all part of the java.util.function package, being used extensively. These interfaces have one abstract method, which is overridden by the lambda expression defined. In this post I will pick Function interface to explain about it in brief and it is one of the interfaces present in java.util.function package. Function interface has two methods: R apply(T t) – Compute the result of applying the function to the input argument default ‹V› Function‹T,V› – Combine with another function returning a function which performs both functions. In this post I would like to write about the apply method, creating APIs which accept these interfaces and parameters and then invoke their corresponding methods. We will also look at how the caller of the API can pass in a lambda expression in place of an implementation of the interface. Apart from passing a lambda expression, the users of the API can also pass method references, about which I havent blogged yet. Function interface is uses in cases where you want to encapsulate some code into a method which accepts some value as an input parameter and then returns another value after performing required operations on the input. The input parameter type and the return type of the method can either be same or different. Lets look at an API which accepts an implementation of Function interface: public class FunctionDemo { //API which accepts an implementation of //Function interface static void modifyTheValue(int valueToBeOperated, Function function){ int newValue = function.apply(valueToBeOperated); /* * Do some operations using the new value. */ System.out.println(newValue); } } Now lets look at the code which invokes this API: public static void main(String[] args) { int incr = 20; int myNumber = 10; modifyTheValue(myNumber, val-> val + incr); myNumber = 15; modifyTheValue(myNumber, val-> val * 10); modifyTheValue(myNumber, val-> val - 100); modifyTheValue(myNumber, val-> "somestring".length() + val - 100); } You can see that the lambda expressions being created accept one parameter and return some value. I will update soon about the various APIs which use this Function interface as a parameter. Meanwhile the complete code is: public class FunctionDemo { public static void main(String[] args) { int incr = 20; int myNumber = 10; modifyTheValue(myNumber, val-> val + incr); myNumber = 15; modifyTheValue(myNumber, val-> val * 10); modifyTheValue(myNumber, val-> val - 100); modifyTheValue(myNumber, val-> "somestring".length() + val - 100); } //API which accepts an implementation of //Function interface static void modifyTheValue(int valueToBeOperated, Function function){ int newValue = function.apply(valueToBeOperated); /* * Do some operations using the new value. */ System.out.println(newValue); } } and the output is: 30 150 -85 -75 In the coming posts I will try to explore the other interfaces present in java.util.function package. Note: The above code was compiled using the JDK downloaded from here and Netbeans 8 nightly builds.
April 6, 2013
by Mohamed Sanaulla
· 12,526 Views
article thumbnail
Java EE 7 and EJB 3.2 support in JBoss AS 8
Some of you might be aware that the Public Final Draft version of Java EE 7 spec has been released. Among various other new things, this version of Java EE, brings in EJB 3.2 version of the EJB specification. EJB 3.2 has some new features compared to the EJB 3.1 spec. I'm quoting here the text present in the EJB 3.2 spec summarizing what's new: The Enterprise JavaBeans 3.2 architecture extends Enterprise JavaBeans to include the following new functionality and simplifications to the earlier EJB APIs: Support for the following features has been made optional in this release and their description is moved to a separate EJB Optional Features document: EJB 2.1 and earlier Entity Bean Component Contract for Container-Managed Persistence EJB 2.1 and earlier Entity Bean Component Contract for Bean-Managed Persistence Client View of an EJB 2.1 and earlier Entity Bean EJB QL: Query Language for Container-Managed Persistence Query Methods JAX-RPC Based Web Service Endpoints JAX-RPC Web Service Client View Added support for local asynchronous session bean invocations and non-persistent EJB Timer Service to EJB 3.2 Lite. Removed restriction on obtaining the current class loader; replaced ‘must not’ with ‘should exercise caution’ when using the Java I/O package. Added an option for the lifecycle callback interceptor methods of stateful session beans to be executed in a transaction context determined by the lifecycle callback method's transaction attribute. Added an option to disable passivation of stateful session beans. Extended the TimerService API to query all active timers in the same EJB module. Removed restrictions on javax.ejb.Timer and javax.ejb.TimerHandle references to be used only inside a bean. Relaxed default rules for designating implemented interfaces for a session bean as local or as remote business interfaces. Enhanced the list of standard activation properties. Enhanced embeddable EJBContainer by implementing AutoClosable interface. As can be seen, some of the changes proposed are minor. But there are some which are useful major changes. We'll have a look at a couple of such changes in this article. 1) New API TimerService.getAllTimers() EJB 3.2 version introduces a new method on the javax.ejb.TimerService interface, named getAllTimers. Previously the TimerService interface had (and still has) a getTimers method. The getTimers method was expected to return the active timers that are applicable for the bean on whose TimerService, the method had been invoked (remember: there's one TimerService per EJB). In this new EJB 3.2 version, the newly added getAllTimers() method is expected to return all the active timers that are applicable to *all beans within the same EJB module*. Typically, an EJB module corresponds to a EJB jar, but it could also be a .war deployment if the EJBs are packaged within the .war. This new getAllTimers() method is a convenience API for user applications which need to find all the active timers within the EJB module to which that bean belongs. 2) Ability to disable passivation of stateful beans Those familiar with EJBs will know that the EJB container provides passivation (storing the state of the stateful bean to some secondary store) and activation (loading the saved state of the stateful bean) capability to stateful beans. However, previous EJB versions didn't have a portable way of disabling passivation of stateful beans, if the user application desired to do that. The new EJB 3.2 version introduces a way where the user application can decide whether the stateful bean can be passivated or not. By default, the stateful bean is considered to be "passivation capable" (like older versions of EJB). However, if the user wants to disable passivation support for certain stateful bean, then the user has the option to either disable it via annotation or via the ejb-jar.xml deployment descriptor. Doing it the annotation way is as simple as setting the passivationCapable attribute on the @javax.ejb.Stateful annotation to false. Something like: @javax.ejb.Stateful(passivationCapable=false) // the passivationCapable attribute takes a boolean value public class MyStatefulBean { .... } Doing it in the ejb-jar.xml is as follows: foo-bar-bean org.myapp.FooBarStatefulBean Stateful false ... Two important things to note in that ejb-jar.xml are the version=3.2 attribute (along with the http://xmlns.jcp.org/xml/ns/javaee/ejb-jar_3_2.xsd schema location) on the ejb-jar root element and the passivation-capable element under the session element. So, using either of these approaches will allow you to disable passivation on stateful beans, if you want to do so. Java EE 7 and EJB 3.2 support in JBoss AS8: JBoss AS8 has been adding support for Java EE 7 since the Public Final Draft version of the spec has been announced. Support for EJB 3.2 is already added and made available. Some other Java EE 7 changes have also made it to the latest JBoss AS 8 builds. To keep track of the Java EE 7 changes in JBoss AS8, keep an eye on this JIRA https://issues.jboss.org/browse/AS7-6553. To use the already implemented features of Java EE 7 in general or EJB 3.2 in particular, you can download the latest nightly build/binary of JBoss AS from here. Give it a try and let us know how it goes. For any feedback, questions or if you run into any kind of issues, feel free to open a discussion thread in our user forum here.
April 5, 2013
by Jaikiran Pai
· 8,826 Views
article thumbnail
Mule and JAXB: turning an XSD file into an XML Fiesta!
Hello friends! How’s it going? Has the following ever happened to you? You show up to work one morning and your boss tells you, “I need you to take this data and turn it into XML.” Well, this has happened to me, and in this blog post I’m going to show you how to do this quickly. XSD? In all fairness to my boss, he did give me an XSD file describing the structure of the XML I was asked to generate. But what is an XSD file anyway? XSD stands for XML Schema Definition. It’s nothing but another XML file of a known and canonical format which is used to describe the structure of another XML file. For example, if I want to dump an employee’s data into an XML, the XSD’s job is to let everyone know that an employee must have a name, an address, a social security number, that he can hold several positions in the same organization and so forth… But most importantly, it describes the layout of all that data in the XML file. Here’s a sample XSD example for your reference describing an employees XML: Generating objects But, who cares? What’s the use of an XSD file? Well, for starters, your IDE probably uses XSD files to validate that the XML files you write are valid (this is true for example when working with Spring, Hibernate, and of course Mule ESB). But it could also be used for automatic mapping and code generation. What JAXB does is to read the XSD file to automatically generate a set of classes that mimic the structure of the XML and that allows for storing the same data in the same way. Once those classes exists, it’s easy for JAXB to marshall XML data into those objects and vice versa. JAXB has a terminal command that takes an XSD file and turns it into a Java Bean. This command is called XJC and is present on the bin/ folder of any JDK installation since version 1.6. Here’s a sample of how to use it: xjc example.xsd The command above will create a java class with the proper JAXB annotations to perform XML marshalling and unmarshalling. It will also create a second class called ObjectFactory, which it will use internally when performing the transformations. You need to add these classes into your project. For simplicity let’s assume that you put them in the package com.mulesoft.example. Then it’s just a matter of populating the bean and using Mule’s JAXB Transformers to generate the XML. Sample code looks as follows: That’s it. You just made your boss happy. Do you really want to impress him though? Let’s also see how you can do the reverse operation and transform an XML file into a Java Object. Mule already provides an object-to-xml-transformer out of the box and it would work just fine in this case, but just for the sake of completeness, let’s see how you can do the same thing using JAX. And that’s it! You’re all set! Now show it to your boss and get him to buy you beer! No related posts.
April 4, 2013
by Mariano Gonzalez
· 11,254 Views
article thumbnail
Promises and Futures in Clojure
Clojure, being designed for concurrency is a natural fit for our Back to the Future series. Moreover futures are supported out-of-the-box in Clojure. Last but not least, Clojure is the first language/library that draws a clear distinction between futures and promises. They are so similar that most platforms either support only futures or combine them. Clojure is very explicit here, which is good. Let's start from promises: Promises Promise is a thread-safe object that encapsulates immutable value. This value might not be available yet and can be delivered exactly once, from any thread, later. If other thread tries to dereference a promise before it's delivered, it'll block calling thread. If promise is already resolved (delivered), no blocking occurs. Promise can only be delivered once and can never change its value once set: (def answer (promise)) @answer (deliver answer 42) answer is a promise var. Trying to dereference it using @answer or (deref answer) at this point will simply block. This or some other thread must first deliver some value to this promise (using deliver function). All threads blocked on deref will wake up and subsequent attempts to dereference this promise will return 42 immediately. Promise is thread safe and you cannot modify it later. Trying to deliver another value to answer is ignored. Futures Futures behave pretty much the same way in Clojure from user perspective - they are containers for a single value (of course it can be a map or list - but it should be immutable) and trying to dereference future before it is resolved blocks. Also just like promises, futures can only be resolved once and dereferencing resolved future has immediate effect. The difference between the two is semantic, not technical. Future represents background computation, typically in a thread pool while promise is just a simple container that can be delivered (filled) by anyone at any point in time. Typically there is no associated background processing or computation. It's more like an event we are waiting for (e.g. JMS message reply we wait for). That being said, let's start some asynchronous processing. Similar to Akka, underlying thread pool is implicit and we simply pass piece of code that we want to run in background. For example to calculate the sum of positive integers below ten million we can say: (let [sum (future (apply + (range 1e7)))] (println "Started...") (println "Done: " @sum) ) sum is the future instance. "Started..." message appears immediately as the computation started in background thread. But @sum is blocking and we actually have to wait a little bit1 to see the "Done: " message and computation results. And here is where the greatest disappointment arrives: neither future nor promise in Clojure supports listening for completion/failure asynchronously. The API is pretty much equivalent to very limited java.util.concurrent.Future. We can create future, cancel it, check whether it is realized? (resolved) and block waiting for a value. Just like Future in Java, as a matter of fact the result of future function even implements java.util.concurrent.Future. As much as I love Clojure concurrency primitives like STM and agents, futures feel a bit underdeveloped. Lack of event-driven, asynchronous callbacks that are invoked whenever futures completes (notice that add-watch doesn't work futures - and is still in alpha) greatly reduces the usefulness of a future object. We can no longer: map futures to transform result value asynchronously chain futures translate list of futures to future of list ...and much more, see how Akka does it and Guava to some extent That's a shame and since it's not a technical difficulty but only a missing API, I hope to see support for completion listeners soon. For completeness here is a slightly bigger program using futures to concurrently fetch contents of several websites, foundation for our web crawling sample: (let [ top-sites `("www.google.com" "www.youtube.com" "www.yahoo.com" "www.msn.com") futures-list (doall ( map #( future (slurp (str "http://" %)) ) top-sites )) contents (map deref futures-list) ] (doseq [s contents] (println s)) ) Code above starts downloading contents of several websites concurrently. map deref waits for all results one after another and once all futures from futures-list all completed, doseq prints the contents (contents is a list of strings). One trap I felt into was the absence of doall (that forces lazy sequence evaluation) in my initial attempt. map produces lazy sequence out of top-sites list, which means future function is called only when given item of futures-list is first accessed. That's good. But each item is accessed for the first time only during (map deref futures-list). This means that while waiting for first future to dereference, second future didn't even started yet! It starts when first future completes and we try to dereference the second one. That means that last future starts when all previous futures are already completed. To cut long story short, without doall that forces all futures to start immediately, our code runs sequentially, one future after another. The beauty of side effects. 1 - BTW (1L to 9999999L).sum in Scala is faster by almost an order of magnitude, just sayin'...
April 1, 2013
by Tomasz Nurkiewicz
· 11,718 Views · 1 Like
article thumbnail
How Does Java Handle Aliasing?
Aliasing means there are multiple aliases to a location that can be updated, and these aliases have different types. In the following example, a and b are two variable names that have two different types A and B. B extends A. B[] b = new B[10]; A[] a = b; a[0] = new A(); b[0].methodParent(); In memory, they both refer to the same location. The pointed memory location are pointed by both a and b. During run-time, the actual object stored determines which method to call. How does Java handle aliasing problem? If you copy this code to your eclipse, there will be no compilation errors. class A { public void methodParent() { System.out.println("method in Parent"); } } class B extends A { public void methodParent() { System.out.println("override method in Child"); } public void methodChild() { System.out.println("method in Child"); } } public class Main { public static void main(String[] args) { B[] b = new B[10]; A[] a = b; a[0] = new A(); b[0].methodParent(); } } But if you run the code, the output would be as follows: Exception in thread “main” java.lang.ArrayStoreException: aliasingtest.A at aliasingtest.Main.main(Main.java:26) The reason is that Java handles aliasing during run-time. During run-time, it knows that the first element should be a B object, instead of A. Therefore, it only runs correctly if it is changed to: B[] b = new B[10]; A[] a = b; a[0] = new B(); b[0].methodParent(); and the output is: override method in Child * original article
March 30, 2013
by Ryan Wang
· 37,174 Views
article thumbnail
HashSet vs. TreeSet vs. LinkedHashSet
in a set, there are no duplicate elements. that is one of the major reasons to use a set. there are 3 commonly used implementations of set in java: hashset, treeset and linkedhashset. when and which to use is an important question. in brief, if we want a fast set, we should use hashset; if we need a sorted set, then treeset should be used; if we want a set that can be read by following its insertion order, linkedhashset should be used. 1. set interface set interface extends collection interface. in a set, no duplicates are allowed. every element in a set must be unique. we can simply add elements to a set, and finally we will get a set of elements with duplicates removed automatically. 2. hashset vs. treeset vs. linkedhashset hashset is implemented using a hash table. elements are not ordered. the add, remove, and contains methods has constant time complexity o(1). treeset is implemented using a tree structure(red-black tree in algorithm book). the elements in a set are sorted, but the add, remove, and contains methods has time complexity of o(log (n)). it offers several methods to deal with the ordered set like first(), last(), headset(), tailset(), etc. linkedhashset is between hashset and treeset. it is implemented as a hash table with a linked list running through it, so it provides the order of insertion. the time complexity of basic methods is o(1). 3. treeset example treeset tree = new treeset(); tree.add(12); tree.add(63); tree.add(34); tree.add(45); iterator iterator = tree.iterator(); system.out.print("tree set data: "); while (iterator.hasnext()) { system.out.print(iterator.next() + " "); } output is sorted as follows: tree set data: 12 34 45 63 now let's define a dog class as follows: class dog { int size; public dog(int s) { size = s; } public string tostring() { return size + ""; } } let's add some dogs to treeset like the following: import java.util.iterator; import java.util.treeset; public class testtreeset { public static void main(string[] args) { treeset dset = new treeset(); dset.add(new dog(2)); dset.add(new dog(1)); dset.add(new dog(3)); iterator iterator = dset.iterator(); while (iterator.hasnext()) { system.out.print(iterator.next() + " "); } } } compile ok, but run-time error occurs: exception in thread "main" java.lang.classcastexception: collection.dog cannot be cast to java.lang.comparable at java.util.treemap.put(unknown source) at java.util.treeset.add(unknown source) at collection.testtreeset.main(testtreeset.java:22) because treeset is sorted, the dog object need to implement java.lang.comparable's compareto() method like the following: class dog implements comparable{ int size; public dog(int s) { size = s; } public string tostring() { return size + ""; } @override public int compareto(dog o) { return size - o.size; } } the output is: 1 2 3 4. hashset example hashset dset = new hashset(); dset.add(new dog(2)); dset.add(new dog(1)); dset.add(new dog(3)); dset.add(new dog(5)); dset.add(new dog(4)); iterator iterator = dset.iterator(); while (iterator.hasnext()) { system.out.print(iterator.next() + " "); } output: 5 3 2 1 4 note the order is not certain. 5. linkedhashset example linkedhashset dset = new linkedhashset(); dset.add(new dog(2)); dset.add(new dog(1)); dset.add(new dog(3)); dset.add(new dog(5)); dset.add(new dog(4)); iterator iterator = dset.iterator(); while (iterator.hasnext()) { system.out.print(iterator.next() + " "); } the order of the output is certain and it is the insertion order. 2 1 3 5 4 6. performance testing the following method tests the performance of the three class on add() method. public static void main(string[] args) { random r = new random(); hashset hashset = new hashset(); treeset treeset = new treeset(); linkedhashset linkedset = new linkedhashset(); // start time long starttime = system.nanotime(); for (int i = 0; i < 1000; i++) { int x = r.nextint(1000 - 10) + 10; hashset.add(new dog(x)); } // end time long endtime = system.nanotime(); long duration = endtime - starttime; system.out.println("hashset: " + duration); // start time starttime = system.nanotime(); for (int i = 0; i < 1000; i++) { int x = r.nextint(1000 - 10) + 10; treeset.add(new dog(x)); } // end time endtime = system.nanotime(); duration = endtime - starttime; system.out.println("treeset: " + duration); // start time starttime = system.nanotime(); for (int i = 0; i < 1000; i++) { int x = r.nextint(1000 - 10) + 10; linkedset.add(new dog(x)); } // end time endtime = system.nanotime(); duration = endtime - starttime; system.out.println("linkedhashset: " + duration); } from the output below, we can clearly wee that hashset is the fastest one. hashset: 2244768 treeset: 3549314 linkedhashset: 2263320 if you enjoyed this article and want to learn more about java collections, check out this collection of tutorials and articles on all things java collections.
March 29, 2013
by Ryan Wang
· 181,623 Views · 3 Likes
article thumbnail
Introduction to Functional Interfaces – A Concept Recreated in Java 8
Any Java developer around the world would have used at least one of the following interfaces: java.lang.Runnable, java.awt.event.ActionListener, java.util.Comparator, java.util.concurrent.Callable. There is some common feature among the stated interfaces and that feature is they have only one method declared in their interface definition. There are lot more such interfaces in JDK and also lot more created by java developers. These interfaces are also called Single Abstract Method interfaces (SAM Interfaces). And a popular way in which these are used is by creating Anonymous Inner classes using these interfaces, something like: public class AnonymousInnerClassTest { public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { System.out.println("A thread created and running ..."); } }).start(); } } With Java 8 the same concept of SAM interfaces is recreated and are called Functional interfaces. These can be represented using Lambda expressions, Method reference and constructor references(I will cover these two topics in the upcoming blog posts). There’s an annotation introduced- @FunctionalInterface which can be used for compiler level errors when the interface you have annotated is not a valid Functional Interface. Lets try to have a look at a simple functional interface with only one abstract method: @FunctionalInterface public interface SimpleFuncInterface { public void doWork(); } The interface can also declare the abstract methods from the java.lang.Object class, but still the interface can be called as a Functional Interface: @FunctionalInterface public interface SimpleFuncInterface { public void doWork(); public String toString(); public boolean equals(Object o); } Once you add another abstract method to the interface then the compiler/IDE will flag it as an error as shown in the screenshot below: Interface can extend another interface and in case the Interface it is extending in functional and it doesn’t declare any new abstract methods then the new interface is also functional. But an interface can have one abstract method and any number of default methods and the interface would still be called an functional interface. To get an idea of default methods please read here. @FunctionalInterface public interface ComplexFunctionalInterface extends SimpleFuncInterface { default public void doSomeWork(){ System.out.println("Doing some work in interface impl..."); } default public void doSomeOtherWork(){ System.out.println("Doing some other work in interface impl..."); } } The above interface is still a valid functional interface. Now lets see how we can use the lambda expression as against anonymous inner class for implementing functional interfaces: /* * Implementing the interface by creating an * anonymous inner class versus using * lambda expression. */ public class SimpleFunInterfaceTest { public static void main(String[] args) { carryOutWork(new SimpleFuncInterface() { @Override public void doWork() { System.out.println("Do work in SimpleFun impl..."); } }); carryOutWork(() -> System.out.println("Do work in lambda exp impl...")); } public static void carryOutWork(SimpleFuncInterface sfi){ sfi.doWork(); } } And the output would be … Do work in SimpleFun impl... Do work in lambda exp impl... In case you are using an IDE which supports the Java Lambda expression syntax(Netbeans 8 Nightly builds) then it provides an hint when you use an anonymous inner class as used above This was a brief introduction to the concept of functional interfaces in java 8 and also how they can be implemented using Lambda expressions.
March 29, 2013
by Mohamed Sanaulla
· 213,309 Views · 18 Likes
article thumbnail
Solving the IBM MQ Client Error – No mqjbnd in java.library.path
if you come across this issue when you try to connect a jms client to ibm mq (v7.0.x.x), this has nothing to do with any environment variables or vm arguments, at least it wasn’t for me (there are quite a lot of those articles out there, that makes you think this is the problem). the fix for this will has to be done on the server side. open the mq explorer. now, if you have not done so already, you need to add your jndi directory to jms administered objects. in the connection factories, you will note that your factories’ transport type is actually “binding”. you need to right-click and go to the switch transport option which will have the “mq client” option that needs to be selected. now the transport type will be “client”. do this to all connection factories that you are connecting to. now, your configuration will look something like below: now, run your client again, and the error should go away. hth.
March 29, 2013
by Tharindu Mathew
· 19,697 Views
article thumbnail
How To Style A Checkbox With CSS
Checkboxes is a HTML element that is possibly used on every website, but most people don't style them so they look the same as on every other site.
March 28, 2013
by Paul Underwood
· 180,118 Views
article thumbnail
Introduction to Default Methods (Defender Methods) in Java 8
We all know that interfaces in Java contain only method declarations and no implementations and any non-abstract class implementing the interface had to provide the implementation. Lets look at an example: public interface SimpleInterface { public void doSomeWork(); } class SimpleInterfaceImpl implements SimpleInterface{ @Override public void doSomeWork() { System.out.println("Do Some Work implementation in the class"); } public static void main(String[] args) { SimpleInterfaceImpl simpObj = new SimpleInterfaceImpl(); simpObj.doSomeWork(); } } Now what if I add a new method in the SimpleInterface? public interface SimpleInterface { public void doSomeWork(); public void doSomeOtherWork(); } and if we try to compile the code we end up with: $javac .\SimpleInterface.java .\SimpleInterface.java:18: error: SimpleInterfaceImpl is not abstract and does not override abstract method doSomeOtherWork() in SimpleInterface class SimpleInterfaceImpl implements SimpleInterface{ ^ 1 error And this limitation makes it almost impossible to extend/improve the existing interfaces and APIs. The same challenge was faced while enhancing the Collections API in Java 8 to support lambda expressions in the API. To overcome this limitation a new concept is introduced in Java 8 called default methods which is also referred to as Defender Methods or Virtual extension methods. Default methods are those methods which have some default implementation and helps in evolving the interfaces without breaking the existing code. Lets look at an example: public interface SimpleInterface { public void doSomeWork(); //A default method in the interface created using "default" keyword default public void doSomeOtherWork(){ System.out.println("DoSomeOtherWork implementation in the interface"); } } class SimpleInterfaceImpl implements SimpleInterface{ @Override public void doSomeWork() { System.out.println("Do Some Work implementation in the class"); } /* * Not required to override to provide an implementation * for doSomeOtherWork. */ public static void main(String[] args) { SimpleInterfaceImpl simpObj = new SimpleInterfaceImpl(); simpObj.doSomeWork(); simpObj.doSomeOtherWork(); } } and the output is: Do Some Work implementation in the class DoSomeOtherWork implementation in the interface This is a very brief introduction to default methods. One can read in depth about default methods here.
March 28, 2013
by Mohamed Sanaulla
· 28,123 Views
article thumbnail
Why We Need Lambda Expressions in Java - Part 1
Lambda expressions are coming to Java 8 and together with Raoul-Gabriel Urma and Alan Mycroft I started writing a book on this topic.
March 27, 2013
by Mario Fusco
· 180,957 Views · 11 Likes
  • Previous
  • ...
  • 425
  • 426
  • 427
  • 428
  • 429
  • 430
  • 431
  • 432
  • 433
  • 434
  • ...
  • Next
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×