Dariusz on Software

Methods and Tools

About This Site

Software development stuff

Archive

Generic Types in Java 1.5
Thu, 25 Mar 2010 09:58:10 +0000

Generics are very useful Java language feature introduced in Java 1.5. Starting from 1.5 you can statically declare expected types of objects inside collections and compiler will enforce this assumption during compilation:

Map<String, BankAccount> bankAccounts = new HashMap<String, BankAccount>();
bankAccounts.put("a1", bankAccount);
bankAccounts.add("a2", "string"); <-- compilation error
Integer x = bankAccounts.get("a1"); <-- compilation error
bankAccounts.put(new Integer("11"), bankAccount); <-- compilation error

Many projects, however, keep 1.4 compatibility mode for many reasons. I think 1.5 is mature enough (ok, let's say that: old) so it may be used safely.

Recently I've started migration from big 1.4 project into 1.5 (in order to introduce generics). I changed Java project compliance level and got the following error:

Java compiler level does not match the version of the installed Java project facet

Quick googling for this error showed the two possible solutions:

  • Right mouse click on project / Properties / Projects Facets / change Java version
  • OR: right click on error in Problems view / Select Quick Fix / Choose 1.5 compiler level

After this fix workspace compiles without errors. Generics can be added now. Eclipse supports this refactoring very well: just select: "Refactor / Infer Generic Type Arguments" and your current file will be filled with generic arguments. Very nice!

And the best at the end: you can select whole project for generic type update - Eclipse will insert generics where possible. It will speed up refactoring greatly!

Tags: java.

Tags

Created by Chronicle v3.5